首页 > 解决方案 > 函数内的 LayoutParam 问题

问题描述

我试图通过将 RelativeLayout.LayoutParams 放在函数中来清理我的 java 代码,这样我就不必每次添加新东西时都创建新的 layoutparams。

问题:我收到错误代码

Unable to start activity ComponentInfo{onedevz.com.noct/onedevz.com.noct.MainActivity}: java.lang.NullPointerException: Layout parameters cannot be null

它说我没有布局参数,即使我有一个并且我在将它放入按钮之前调用了它。这是代码

public class MainActivity extends AppCompatActivity {

    MicButton micbutton;
    Button menuBtn,onBtn;
    EditText text;
    RelativeLayout relativeLayout;
    RelativeLayout.LayoutParams lp1,lp2,lp3,lp4;
    boolean clicked;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

// Creating a new RelativeLayout
        relativeLayout = new RelativeLayout(this);

        // Defining the RelativeLayout layout parameters.
        // In this case I want to fill its parent
        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT,
                RelativeLayout.LayoutParams.FILL_PARENT);

// Defining the layout parameters of the TextView
        placement(lp1,100,100,0,200,40,0,RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
        placement(lp2,100,100,0,350,40,0,RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
        placement(lp3,100,100,0,500,40,0,RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
        placement(lp4,100,ViewGroup.MarginLayoutParams.MATCH_PARENT,150,0,40,0,RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.CENTER_HORIZONTAL);

        setParameter();

        addView();
// Setting the RelativeLayout as our content view
        setContentView(relativeLayout, rlp);
}
   void placement(RelativeLayout.LayoutParams name,int height,int width,int topMargin,int bottomMargin,int leftMargin,int rightMargin,int rule1,int rule2){
        name = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        name.addRule(rule1);
        name.addRule(rule2);
        name.leftMargin = leftMargin;
        name.bottomMargin = bottomMargin;
        name.height = height;
        name.width = width;
    }

    void setParameter(){
        // Setting the parameters on the TextView
        micbutton.setLayoutParams(lp1);
        onBtn.setLayoutParams(lp2);
        menuBtn.setLayoutParams(lp3);
        text.setLayoutParams(lp4);
    }

    void addView(){
        // Adding the TextView to the RelativeLayout as a child
        relativeLayout.addView(micbutton);
        relativeLayout.addView(text);
    }
}

任何帮助将不胜感激,谢谢。

标签: javaandroidandroid-layoutparams

解决方案


您的LayoutParameterslp1,lp2,lp3,lp4 尚未初始化。初始化它们,然后将其设置为TextView.


推荐阅读