使用addView动态添加按钮不起作用

时间:2016-03-27 13:47:18

标签: 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);
        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);
    }
});

1 个答案:

答案 0 :(得分:0)

首先用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"));}


});
}