如何在当前活动中获取视图(属于另一个活动)的视图的高度和宽度。例如。活动一中有一个按钮,我必须借助活动ID获得活动二中按钮的属性。(我考虑过视图,因为它可以是ImageView,TextView,WebView或其他任何东西)。
在这里,我粘贴了我尝试过的代码。
公共类SecAct扩展了活动{
ArrayList<Integer> butList1;
RelativeLayout help;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
help = (RelativeLayout)findViewById(R.id.helplay);
createWidgets();
}
private void createWidgets() {
// TODO Auto-generated method stub
butList1=MainActivity.butList;
int a=butList1.get(0);
View v=(View)(findViewById(a));
int width=v.getWidth();
int height=v.getHeight();
help.addView(v);
System.out.println("id is "+ width);
}
public void close(View v){
finish();
}
}
我能够获取a的值,但是我无法获取v(View)的属性,即高度,宽度或ID等,我得到了空指针异常。
首先从视图的活动中获取上下文,例如:
public static Context con;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
con = this;
}
然后,在另一个活动中:
Context context = FIRST_ACTIVITY.con;
Activity firstActivy = (Activity) context;
ViewGroup firstActivityView = firstActivy.getWindow().getDecorView().findViewById(android.R.id.content);
View DISIRED_VIEW = firstActivityView.findViewById(R.id.DISIRED_VIEW_ID);
最后,获取宽度和高度:
int width = DISIRED_VIEW.getWidth();
int height = DISIRED_VIEW .getHeight();
也许这些值(宽度和高度)可以为0,所以您必须这样做:
final int width, height;
DISIRED_VIEW.post(new Runnable() {
@Override
public void run() {
width = DISIRED_VIEW.getWidth();
height = DISIRED_VIEW.getHeight();
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句