2016-03-27 66 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でレイアウトを定義し、それにIDを与え、 は、XMLでのLinearLayoutを定義している、あなたはそれがJavaコードで

をMyLayoutと呼ばれることを前提としていLinearLayoutをグローバル変数として定義し、onCreateメソッドで次のように初期化します。

関連する問題