使用getWindowManager()的NullPointerException

时间:2015-05-24 07:22:18

标签: java android

为什么SAMPLE1代码工作正常并且SAMPLE2抛出 NullPointerException ? do getWindowManager()只能在 onCreate 中工作?我该怎么做才能创建一个方法来返回视图的高度并使其可用于所有子类?请帮忙..

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;
    }
        }

2 个答案:

答案 0 :(得分:1)

您永远不应该致电new MainActivity(),而是尝试传递或使用上下文,例如MainActivity.this

答案 1 :(得分:1)

更改此行:

>  im.getLayoutParams().height = new MainActivity().heightof();

到这一行:

  

im.getLayoutParams()。height = heightof();