2012-04-26 7 views
0

ユーザーにボタンを追加させたい 各行が4つのボタンになるようにします。ボタンを動的に追加する方法

private void addContact() { 
     //numButton Count how many buttons there are in line 
     if(numButton==0){ 
      LinearLayout linearLayout =new LinearLayout(this); 
      linearLayout.setOrientation(0);//horizontal 
      ImageButton imageButton =new ImageButton(this); 
      imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1)); 
      linearLayout.addView(imageButton); 
      LinearLayout linearbase= (LinearLayout)findViewById(R.id.linearBase); 
      linearbase.addView(linearLayout); 
      numButton++; 
     } 
     else if(numButton<4) 
     { 
      LinearLayout linearlayout= ----####Here I do not know what to write!!!!### 
      ImageButton imageButton =new ImageButton(this); 
      imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1)); 
      linearlayout.addView(imageButton); 
      numButton++; 
     } 
     else 
     { 
      numButton=0; 
     } 
    } 

が、私は私の問題は、具体的に私の問題は、どのようにこの関数の以前の呼び出しで定義されているのLinearLayoutに新しいボタンを配置することです コードの行をマーク: ので、私は次の関数を書きましたか? 2番目の質問:アプリケーションを終了しても新しい状況を維持する方法

+0

:[動的にボタンを作成し、onClickListener設定](http://stackoverflow.com/questions/4401028/dynamically - 作成ボタンと設定オンクリックリスナー)私は**関連**の列(そこに - >)でそれを見つけました。アプリを終了した後にデータを保持することに関しては、これは良い参考資料です。 [データストレージ](http://developer.android.com/guide/topics/data/data-storage.html) – Sam

答えて

0

初めてLinearLayoutを作成するときは、idを付けます。次に、findViewById()を使用して2回目を取得できます。 2番目の質問に答えるには、SharedPreferencesにブール値を格納します。

0

LinearLayoutsをaddContactメソッドの外に宣言します。そうでない場合は、そのメソッド内にのみ存在します。私は(私はそれをテストしていない)、このような何かが動作するはずだと思う:これは役立つかもしれない

class myclass{ 

    private LinearLayout linearLayout; 
    private LinearLayout linearbase; 
    private int numButton; 

    @Override 
    public void onFinishInflate() { 
     super.onFinishInflate(); 

     linearbase= (LinearLayout)findViewById(R.id.linearBase); 
     LinearLayout linearLayout =new LinearLayout(this); 
     linearLayout.setOrientation(0);//horizontal 

     numButton=0; 
    } 

    private void addContact() { 
     //numButton Count how many buttons there are in line 
     if(numButton==0){ 

      ImageButton imageButton =new ImageButton(this); 
      imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1)); 
      linearLayout.addView(imageButton); 
      linearbase.addView(linearLayout); 
      numButton++; 
     } 
     else if(numButton<4) 
     { 
      linearLayout= new LinearLayout(this); 
      ImageButton imageButton =new ImageButton(this); 
      imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1)); 
      linearlayout.addView(imageButton); 
      numButton++; 
     } 
     else 
     { 
      numButton=0; 
     } 
    } 
} 
+0

それは私の/ –

関連する問題