我正在使用下面显示的这种技术,因为在创建视图之前我必须等待才能获得宽度和高度。或者它会导致nullpointerexcepion。
所以我使用下面的示例1,它通过将一个runnable发布到frameLayout来完美地工作,这样在创建frameLayout之后它将获得宽度和高度。
但是例如2它不起作用并导致nullpointer异常,因为两种技术都是相同的错误?有更好的方法吗?
exmaple 1,没有任何问题
frameLayoutOne = (FrameLayout) findViewById(R.id.frameLayout1);
frameLayoutOne.post(new Runnable(){
public void run(){
widthofit = frameLayoutOne.getWidth();
heightofit = frameLayoutOne.getHeight();
Toast.makeText(MainActivity.this, "width 1 is: " + widthofit , Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "height 1 is: " + heightofit , Toast.LENGTH_SHORT).show();
}
});
示例2,结果为nullpointerexception
ViewGroup contentViewObj = (ViewGroup) getContentView();
contentViewObj.post(new Runnable(){ // <-- NULL POINTER ON THIS LINE
public void run(){
final ActionBar actionBar = getActionBar();
if(actionBar!=null){
if(actionBar.isShowing()) {
int actionBarHeightNow = actionBar.getHeight();
Toast.makeText(MainActivity.this, "total height of actionbar currently: " + actionBarHeightNow, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "actionBar is not showing version 1", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this, "actionBar is not showing version 2", Toast.LENGTH_LONG).show();
}
}
});