2010-09-12 106 views
2

我拼命試圖以編程方式設置表格中的單元格的TextView屬性,但無法讓它工作!每當我設置佈局屬性,該字段將不會出現(但不會給出任何錯誤或例外)。我boilded下來到這個簡單的例子:如何設置(文本)以編程方式查看屬性?

package mmo.application.listpro; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.LinearLayout; 
import android.widget.TableLayout; 
import android.widget.TableRow; 
import android.widget.TextView; 

public class Test extends Activity 
{ 
    @Override 
    public void onCreate(final Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     TableLayout table = new TableLayout(this); 
     TableRow row = new TableRow(this); 
     for (String label: new String[] {"field1", "field2", "field3"}) { 
      TextView tv = new TextView(this); 
      tv.setText(label); 
//   LinearLayout.LayoutParams lp = 
//    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
//           LinearLayout.LayoutParams.WRAP_CONTENT); 
//   lp.setMargins(2, 2, 2, 2); // left/top/right/bottom 
//   tv.setLayoutParams(lp); 
      row.addView(tv); 
     } 
     table.addView(row); 
     setContentView(table); 
    } 
} 

這將顯示三個字段,但是當你取消註釋五註釋行,那麼什麼都不會出現。爲什麼?爲什麼設置佈局參數導致我的TextView沒有出現?我卡住了!我錯過了什麼?

邁克爾

PS:這裏的清單,如果某種靈魂迅速想嘗試了這一點:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="mmo.application.listpro" android:versionCode="1" android:versionName="Development"> 
    <application 
     android:icon="@drawable/icon" 
     android:label="@string/app_name" 
     android:debuggable="true"> 
     <activity 
      android:label="test" 
      android:name=".Test" 
      android:screenOrientation="portrait"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 
    <uses-sdk android:targetSdkVersion="8" android:minSdkVersion="8" /> 
</manifest> 
+0

一般來說,我會建議儘可能在佈局XML中做這種事情。雖然我意識到有時候不是,在這種情況下,理解發生的事情是很好的,所以這仍然是一個值得考慮的問題。 – MatrixFrog 2010-09-12 23:43:34

+0

對!在我的情況下,實際的顯示取決於字段的類型(我的應用程序中有大約10個不同的「類型」),所以我需要以編程方式創建它們。 – mmo 2010-09-14 12:11:44

回答

6

TableRow always enforces those values to be respectively MATCH_PARENT and WRAP_CONTENT。所以你只需要創建默認的TableRow.LayoutParams,設置邊距並將其應用於TextView。

TableRow.LayoutParams lp = new TableRow.LayoutParams(); 
lp.setMargins(2, 2, 2, 2); 
row.addView(tv, lp);;

+0

這個伎倆!我沒有意識到每個佈局/視圖都有它自己的LayoutParams類型。所以我顯然選擇了錯誤的......什麼都讓我感到厭煩:TableLayout和TableRow都從LinearLayout繼承。但TableRow.LayoutParameters顯然不能從LinearLayout.LayoutParameters繼承,所以顯然他們被簡單地忽略了... – mmo 2010-09-14 12:23:40

+1

Excellento bhups! – makki 2012-04-13 10:39:43

0

TextView S中的直接父是TableRow不是TableLayout,所以在使用TableRow.LayoutParams而不是TableLayout.LayoutParams

相關問題