2012-06-23 127 views
0

我試圖動態地創建一個TableLayout。我想創建3X3的行和列。如何在android中動態創建TableLayout?


public class PortAFareActivity extends Activity { 

@Override 

public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    TableLayout seatTable=new TableLayout(this);   
    ImageButton[][] seatButton=new ImageButton[3][3]; 
    seatTable.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
    TableRow[] seatRow=new TableRow[3];   
    for (int i = 0; i < 3; i++) { 
     seatRow[i]=new TableRow(this); 
     seatRow[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));   
     for (int j = 0; j < 3; j++) {    
      seatButton[i][j]=new ImageButton(this); 
      seatButton[i][j].setImageResource(R.drawable.seat);    
      seatButton[i][j].setLayoutParams(new LayoutParams(50,30)); 
      seatRow[i].addView(seatButton[i][j]); 
     } 
     seatTable.addView(seatRow[i]); 
    } 
    LinearLayout lin=(LinearLayout)findViewById(R.id.linLayout); 
    lin.addView(seatTable,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
    lin.invalidate(); 
    Toast.makeText(this, " "+seatTable.getChildCount() , Toast.LENGTH_SHORT).show();  
} 
} 

我的佈局XML文件包含ID linLayout

任何幫助一個LinearLayout中,將不勝感激。 =)

+0

我後回答問題是...的LayoutParams我 –

回答

0

試試這個它會工作

public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.registration); 

    TableLayout seatTable=new TableLayout(this); 
    ImageButton[][] seatButton=new ImageButton[3][3]; 
    seatTable.setBackgroundColor(Color.RED); 
    seatTable.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 
    TableRow[] seatRow=new TableRow[3]; 
    for (int i = 0; i < 3; i++) { 
     seatRow[i]=new TableRow(this); 
     seatRow[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
     for (int j = 0; j < 3; j++) { 
      seatButton[i][j]=new ImageButton(this); 
      seatButton[i][j].setImageResource(R.drawable.seat); 
      //seatButton[i][j].setLayoutParams(new LayoutParams(50,30));//<--------problem 
      seatRow[i].addView(seatButton[i][j]); 
     } 
     seatTable.addView(seatRow[i]); 
    } 
    LinearLayout lin=(LinearLayout)findViewById(R.id.linLayout); 
    lin.addView(seatTable);//<-------- not the problem but not required 
    lin.invalidate(); 
    Toast.makeText(this, " "+seatTable.getChildCount() , Toast.LENGTH_SHORT).show(); 
} 
+0

已經打上<--------- –

+0

感謝好友的問題行!謝謝一噸=) –

+0

永遠歡迎...... :) –

相關問題