设置LayoutParams时出现NullPointerException

sno*_*rot 6 java android android-layout

我想以编程方式添加一个按钮,也应该设置LayoutParams.不幸的是,该应用程序提供了一个例外:

java.lang.NullPointerException:尝试在空对象引用上写入字段'int android.view.ViewGroup $ LayoutParams.height'

我不知道为什么.你可以帮帮我吗?这是我的代码.

 Button b = new Button(getApplicationContext());
        b.setText(R.string.klick);
        ViewGroup.LayoutParams params = b.getLayoutParams();
        params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
Run Code Online (Sandbox Code Playgroud)

Dmi*_*fti 12

由于您以编程方式创建Button,b因此不会设置任何布局参数.所以你需要像这样手动设置它们:

ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)

或者至少在更改它们之前检查params是否为空

    ViewGroup.LayoutParams params = b.getLayoutParams();
    if (params != null) {
        params.width= ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
    } else
        params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Run Code Online (Sandbox Code Playgroud)