Java Android:如何通过点击按钮添加复选框?
我试图通过按下“添加”按钮(b1),将复选框添加到我的线性布局中。 我的应用程序一直在线Java Android:如何通过点击按钮添加复选框?,java,android,checkbox,android-linearlayout,add,Java,Android,Checkbox,Android Linearlayout,Add,我试图通过按下“添加”按钮(b1),将复选框添加到我的线性布局中。 我的应用程序一直在线l1.addView(ckbx)上崩溃(日志显示“此处”,但不显示“此处2”)。 有什么想法吗 谢谢:) 这是我的代码: package com.example.todolist; import android.os.Bundle; import android.app.ActionBar.LayoutParams; import android.app.Activity; import android.u
l1.addView(ckbx)上崩溃代码>(日志显示“此处”,但不显示“此处2”)。
有什么想法吗
谢谢:)
这是我的代码:
package com.example.todolist;
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private LinearLayout l1;
private EditText e1;
private Button b1;
private Button b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1 = (LinearLayout)findViewById(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText1);
b1 = (Button)findViewById(R.id.button1);
b2 = (Button)findViewById(R.id.button2);
// Buttons should register with listener
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick (View v) {
switch(v.getId())
{
// Starts Service.class
case R.id.button1:
Toast.makeText(this, "Add pressed", Toast.LENGTH_SHORT).show();
// Create new check box in layout
CheckBox ckbx = createNewCheckBox(e1.getText().toString());
Log.d("here","here now");
l1.addView(ckbx);
Log.d("here 2","here now 2");
setContentView(l1);
break;
case R.id.button2:
Toast.makeText(this, "Delete pressed", Toast.LENGTH_SHORT).show();
break;
}
}
// User defined method to create a new check box in the linear layout page
private CheckBox createNewCheckBox(String text) {
final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final CheckBox checkBox = new CheckBox(this);
checkBox.setLayoutParams(lparams);
checkBox.setText(text);
return checkBox;
}
}
l1=(LinearLayout)findViewById(R.layout.activity\u main)代码>
改为
l1 = (LinearLayout)findViewById(R.id.yourlinearlayoutidfromxml);
您还应该将stacktace与问题一起发布,因为记录了有关崩溃的相关信息。可疑NullpointerException
对于同一个活动,您有两次setContentView
,这不是一个好的设计
setContentView(R.layout.activity_main);
你已经有了
l1 = (LinearLayout)findViewById(R.id.yourlinearlayoutidfromxml);
你应该删除
setContentView(l1);