爲什麼SAMPLE1代碼工作正常並且SAMPLE2拋出NullPointerException? 做getWindowManager()
只在onCreate工作?我能做些什麼來創建一個方法,將返回視圖的高度,並使其可用於所有的子類?請幫助..使用getWindowManager()的NullPointerException()
SAMPLE1
public class MainActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int height = displaymetrics.heightPixels;
float imheight= (float) (height*.4);
int h=Math.round(imheight);
ImageView im=(ImageView)findViewById(R.id.mainnews1);
im.getLayoutParams().height = h;
im.setScaleType(ImageView.ScaleType.FIT_XY);
}
SAMPLE2
public class MainActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView im=(ImageView)findViewById(R.id.mainnews1);
im.getLayoutParams().height = new MainActivity().heightof();
im.setScaleType(ImageView.ScaleType.FIT_XY);
}
public int heightof()
{
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
final int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
float imheight= (float) (height*.4);
int h=Math.round(imheight);
return h;
}
}
可以üplz後如何做? –
你已經在你的'MainActivity'上下文中,所以你可以簡單地使用它的任何方法。 ''new MainActivity()。heightof();'是不需要的,只有'heightof()'或'this.heightof()'或者MainActivity.this.heightof()'才能正常工作 – Mithun
哦對不起..我的錯誤。 .thanks ... :-) –