2014-02-28 32 views
0

我想在Android中平分兒童中的TableRow空間。這是我迄今完成的屏幕。 enter image description hereAndroid中平分TableRow空間的代碼

我希望「文本1文本1文本1」的行佔用相等的空間量。我想從java代碼中完成。我的java代碼如下:

public class History extends Activity implements View.OnClickListener { 
    int counter=0; 
    TableLayout TL ; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.history);   

     Button b1 = (Button) findViewById(R.id.Button01); 
     b1.setOnClickListener(this); 
    } 

    public void onClick(View arg0) { 
     TableLayout TL = (TableLayout) findViewById(R.id.table_layout); 
     TableRow row = new TableRow(this); 
     counter++; 

     TextView t = new TextView(this); 
     t.setText("text " + counter); 

     TextView t1 = new TextView(this); 
     t1.setText("text " + counter); 

     TextView t2 = new TextView(this); 
     t2.setText("text " + counter); 

     // add the TextView and the CheckBox to the new TableRow 

     row.addView(t); 
     row.addView(t1); 
     row.addView(t2); 
     TL.addView(row,new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); 
    } 
} 

我想實現以下屏幕。 enter image description here 我能做些什麼來實現我的目標?

+0

'TableLayout'有一個'setStretchAllColumns()'方法。 – Luksprog

+0

您可能會發現此鏈接有幫助 http://stackoverflow.com/a/4577669/1295906 – Smittey

回答

2

你想用在TableRowweightweightSum和我們TextView通過TableLayout.LayoutParams設置爲做到這一點。下面是一些帶有相關注釋的示例代碼:

TableRow row = new TableRow(this); 
row.setLayoutParams(
    new TableLayout.LayoutParams((LayoutParams.MATCH_PARENT, 
            LayoutParams.WRAP_CONTENT)) 
// Set the weightSum of the row 
row.setWeightSum(1f); 

// Set the layout and weight for the columns. Note 0.5f gives us 0.5f+0.5f = 1f, 
// the weightSum set above. (Using two rows as an example). 
TableLayout.LayoutParams layoutParams = 
     new TableLayout.LayoutParams(0, 
         LayoutParams.LayoutParams.WRAP_CONTENT, 0.5f); 

TextView t1 = new TextView(this); 
t1.setText("text " + counter); 
// Set our layoutParams 
t1.setLayoutParams(layoutParams); 

TextView t2 = new TextView(this); 
t2.setText("text " + counter); 
// Set our layoutParams 
t2.setLayoutParams(layoutParams); 

// Add views to row 
row.addView(t1); 
row.addView(t2); 
// Add row to table 
TL.addView(row); 
+0

粘貼此代碼後,我看到沒有行添加。 –

+0

@osimer pothe錶行是LinearLayout的子項,因此您可以使用LinearLayout屬性WeightSum和weight.It將解決您的問題。選項... –

+0

我還沒有理解您的解決方案。 –