2011-07-29 8 views

答えて

3

これを試して、あなたが探しているものかどうかを確認できます。

main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/layout" android:orientation="vertical" 
android:layout_width="fill_parent" android:layout_height="fill_parent" 
> 
    <Button android:text="Button" android:id="@+id/button1" 
    android:layout_height="wrap_content"  
    android:layout_width="wrap_content"/> 
    <TableLayout android:id="@+id/tableLayout1" 
    android:layout_height="wrap_content" android:layout_width="fill_parent" /> 
</LinearLayout> 

あなたのActivityクラス:

public class mainActivity extends Activity implements OnClickListener { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     Button b = (Button) findViewById(R.id.button1); 
     b.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) { 
     TableLayout table = (TableLayout) findViewById(R.id.tableLayout1); 

     int buttonsInRow = 0; 
     int numRows = table.getChildCount(); 
     TableRow row = null; 
     if(numRows > 0){ 
      row = (TableRow) table.getChildAt(numRows - 1); 
      buttonsInRow = row.getChildCount();   
     } 

     if(numRows == 0 || buttonsInRow == 3){ 
      row = new TableRow(this); 
      table.addView(row); 
      buttonsInRow = 0; 
     } 
     if(buttonsInRow < 3){ 
      Button b = new Button(this); 
      row.addView(b, 100, 50); 
     } 
    } 
} 

はそれがお役に立てば幸いです。

+0

これはまさに私が探していたものでした!!!!!あなたはそれを推測していないかもしれませんが、私はアンドロイドの相対的なnewbyであり、.getChildAt()または.getChildCount()の使い方を知りませんでした。しかし今、私はそうやっています。 – grebwerd

+0

私は同様の問題を抱えていました.1つのボタンのtablerowにボタンを追加するか、すでに2つのボタンがある場合は新しいtablerowを作成します。このコードは完璧でした。 – georgiecasey

+0

これは私を助けました。また、ボタンの生成を自動化したい場合は、forループに入れるだけです。追加するボタンの数を制限するだけです。 – Razgriz

1

レイアウトはあなたが動的に行を追加したいTableLayout.Ifで、その行のボタンは既にレイアウト内の行を持っている場合は、単に行をフェッチし、追加follwoingコード

TableRow tr1=new TableRow(this); 
        Button tv=new Button(this); 
       tv.setText(""); 
       tr1.addView(tv,250,30); 
       Button tv1=new Button(this); 
       tv1.setText(""); 
       tr1.addView(tv1,100,30); 
       layout.addView(tr1); 

を使用することができますボタンを

+0

多くのおかげさまですが、私はより具体的にすべきでした。 1行に3つのボタンを追加するボタンをクリックしたいと思います。最初の行がいっぱいになると、新しい行が作成され、新しいボタンが追加されます。 – grebwerd

+0

OKこのコードは、行とボタンを動的に追加する方法を示しています。必要に応じて変更してください。 – Rasel

関連する問題