将TextView宽度设置为0dp不起作用

时间:2011-10-16 13:28:20

标签: android textview

如何以编程方式将TextView的宽度设置为0dp?我试图将LinearLayout加入一对TextViews,但所有宽度相同,当我放入xml之类的

<LinearLayout 
android:layout_width="fill_parent"
android:layout_height="wrap_content"
 >
 <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left"
android:gravity="left"
                    />
 <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
        />
 <TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="test"
android:layout_gravity="right"
android:gravity="right"
        />
</LinearLayout>

但在代码中尝试

TextView txtTemp = new TextView(this);
txtTemp.setText(captures.get(i));
LinearLayout.LayoutParams tempLL = (LinearLayout.LayoutParams) txtTemp
                        .getLayoutParams();
tempLL.width =0;
tempLL.height = LinearLayout.LayoutParams.WRAP_CONTENT;
tempLL.weight = 1;

if (i == 0) {
    tempLL.gravity = Gravity.LEFT;
        }
if (i == (captures.size() - 1)) {
    tempLL.gravity = Gravity.RIGHT;
} else {
    tempLL.gravity = Gravity.CENTER;
                }
    txtTemp.setLayoutParams(tempLL);

我在tempLL.width null异常上遇到异常。怎么解决这个?

1 个答案:

答案 0 :(得分:2)

而不是使用

LinearLayout.LayoutParams tempLL = (LinearLayout.LayoutParams) txtTemp
                    .getLayoutParams();
            tempLL.width =0;
            tempLL.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            tempLL.weight = 1;

试试这个

LinearLayout.LayoutParams tempLL = new LinearLayout.LayoutParams(0,
        LayoutParams.WRAP_CONTENT,1.0);
txtTemp.setLayoutParams(tempLL);

您正在创建新的textview,但尚未指定layoutparams。所以getLayoutParams应该返回null。因此,创建一个新的layoutparam对象并将其设置为新的textview。

相关问题