设置TextView的宽度0dp不起作用 [英] Set TextView width to 0dp doesn't work

查看:520
本文介绍了设置TextView的宽度0dp不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置编程宽度的TextView的是0dp?我试图把在的LinearLayout夫妇TextViews但都以相同的宽度,当我把XML像

How to set programmatically width of TextView to be 0dp ? I am trying to put in LinearLayout couple TextViews but all to be same width, and when I put in xml like

<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>

但是当code尝试像

but when in code try like

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空例外了异常。如何解决此问题?

I got exception on tempLL.width null exception. How to solve this ?

推荐答案

而不是使用

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。

You are creating a new textview and there is no layoutparams specified yet. So getLayoutParams should return null. So create a new layoutparam object and set that to the new textview.

这篇关于设置TextView的宽度0dp不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆