该应用无法启动

时间:2017-11-29 09:14:07

标签: java android xml

我想制作一个新的EditText,当我点击它一直崩溃的按钮时,我不知道为什么? (我对此很新)

private Button addButton;
private LinearLayout addLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addButton = (Button) findViewById(R.id.button);

    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
            EditText editText = new EditText(getApplicationContext());
            editText.setLayoutParams(params);
            addLayout.addView(editText);


        }
    });
}

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

您忘记绑定 addLayout

试试这个

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addButton = (Button) findViewById(R.id.button);

    // bind your LinearLayout here 
    addLayout = (LinearLayout) findViewById(R.id.addLayout);

    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
            EditText editText = new EditText(getApplicationContext());
            editText.setLayoutParams(params);
            addLayout.addView(editText);


        }
    });
}