Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用addView动态添加按钮不会';行不通_Java_Android Layout_View - Fatal编程技术网

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


});
}