Java 使用addView动态添加按钮不会';行不通
下面的代码是我程序的一部分。当我单击按钮Java 使用addView动态添加按钮不会';行不通,java,android-layout,view,Java,Android Layout,View,下面的代码是我程序的一部分。当我单击按钮sunday时,我希望创建4个按钮。但是,它在addView部分崩溃: sunday.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LinearLayout lay (LinearLayout)v.findViewById(R.id.lay_schedule); Butto
sunday
时,我希望创建4个按钮。但是,它在addView
部分崩溃:
sunday.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
LinearLayout lay (LinearLayout)v.findViewById(R.id.lay_schedule);
Button btnS1 = new Button(getContext());
Button btnS2 = new Button(getContext());
Button btnS3 = new Button(getContext());
Button btnS4 = new Button(getContext());
btnS1.setText("Add Your Lesson");
btnS2.setText("Add Your Lesson");
btnS3.setText("Add Your Lesson");
btnS4.setText("Add Your Lesson");
lay.addView(btnS1);
lay.addView(btnS2);
lay.addView(btnS3);
lay.addView(btnS4);
}
});
首先用XML定义布局并给它一个ID, 假设您已经在xml中定义了LinearLayout,并将其称为MyLayout 在java代码中,将LinearLayout定义为全局变量,并在onCreate方法下对其进行初始化,如下所示
public class MyClass extends Activity{
LinearLayout myLinear;
Button myButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLinear=(LinearLayout)findViewById(R.id.myLinear)// as we defined linear layout in xml
myButton=(Button)findViewById(R.id.myButton);
myBtton.setOnClickListener(new OnClickListener(public void onClick(View v){
this.myLinearLayout.addView(new Button("My text"));}
});
}