2012-05-29 51 views
1

我通過代碼動態創建TableLayout,並希望在列之間設置邊距。我的TableRows包含的唯一類型的內容是TextViews。Android:設置TableRow內容的邊距(意味着:列之間的邊距)

我的意圖是在每個TextView上放置一個簡單的android:layout_marginRight。但我想通過xml而不是代碼來定義這個。

我的嘗試:

代碼:

txtView.setTextAppearance(context, R.style.TableTextView); 
txtView.setText(content); 
tableRow.addView(txtView); 

的XML

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <style name="TableTextView"> 
     <item name="android:textAppearance">?android:attr/textAppearanceLarge</item> 
     <item name="android:textStyle">bold</item> 
     <item name="android:layout_marginRight">5dip</item> 
    </style> 
</resources> 

會發生什麼:

layout_marginRight集的XML不起作用,但textAppearancetextStyle在XML d中設置工作。我假設setTextAppearance-method是爲TextView分配邊距的錯誤方法?如果我可以通過XML(如我上面試過的)代替Java代碼,那將會非常好。

謝謝!

回答

1

發生這種情況是因爲您將樣式設置爲文本本身而不是TextView元素。 您應該在XML中設置元素樣式。它也可以通過代碼實現,但我認爲最好在XML佈局文件中這樣做。

喜歡的東西:

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    style="@style/mTableTextView" /> 

關於設置從代碼中,我不是專家,但我明白,你能以某種方式充氣。 查看ThisThis的問題。

+0

Thx,看起來不錯,但我該如何將它應用到我的動態生成的TextView對象?問題是我需要使用Java而不是XML來創建TextViews,因爲我的表格中TextView的數量不是靜態的,並且可能會不時變化。 – alapeno

+0

你可以誇大它,我不是一個expe but,但修改後的答案與鏈接 –

1

你想給

android.widget.TableRow.LayoutParams param = new android.widget.TableRow.LayoutParams(); 
param.rightMargin = Converter.dpToPixel(10, getContext()); // right-margin = 10dp 
button.setLayoutParams(param); 

// Converter: 
private static Float scale; 
public static int dpToPixel(int dp, Context context) { 
    if (scale == null) 
     scale = context.getResources().getDisplayMetrics().density; 
    return (int) ((float) dp * scale); 
} 

可以設置的值表參數不同之間的餘量。

+0

謝謝,我會嘗試這個,如果通過XML(我更喜歡)的方式將無法正常工作。 – alapeno

+1

如果它可以幫助你!請appriciate – MobileEvangelist