我通过代码动态创建一个TableLayout,并希望在列之间设置边距。我的 TableRows 包含的唯一内容类型是 TextViews。
我的目的是在每个文本视图上放置一个简单的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>
发生什么:
XML 中设置的layout_marginRight
不起作用,但 XML 中设置的textAppearance
和textStyle
起作用。我认为 setTextAppearance-方法是为文本视图分配边距的错误方法?如果我可以通过XML(就像我上面尝试的那样)而不是Java代码来做到这一点,那就太好了。
谢谢!
发生这种情况是因为您将样式设置为文本本身,而不是 TextView 元素。您应该在 XML 中设置元素样式。也可以从代码中实现这一点,但我认为最好在 XML 布局文件中执行此操作。
像这样:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/mTableTextView" />
关于从代码中设置它,我不是专家,但我知道你可以以某种方式膨胀它。看看这个,还有这个问题。
你想在列之间留出边距
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);
}
您可以设置不同的值表参数。