我正在尝试通过按下“添加”按钮(b1)为我的linearlayout添加一个复选框。
我的应用程序一直在线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;
}
}
答案 0 :(得分:0)
l1 = (LinearLayout)findViewById(R.layout.activity_main);
更改为
l1 = (LinearLayout)findViewById(R.id.yourlinearlayoutidfromxml);
您还应该发布堆栈以及问题,因为会记录有关崩溃的相关信息。怀疑NullpointerException
。
对于相同的活动,你也有setContentView
两次,这不是一个好的设计。
setContentView(R.layout.activity_main);
你已经拥有
l1 = (LinearLayout)findViewById(R.id.yourlinearlayoutidfromxml);
你应该删除
setContentView(l1);