2016-03-27 4 views
0

Код ниже является частью моей программы. Когда я нажимаю на кнопку sunday, я хочу, чтобы были созданы 4 кнопки. Тем не менее, он выходит из строя в addView части:Добавление динамических кнопок с помощью 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); 
    } 
}); 

ответ

0

первая вещь определить макет в XML и дать ему идентификатор, предположим, что вы определили LinearLayout в XML, и вы назвали его 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"));} 


}); 
}