【问题标题】:Android - Why is the TextView shown as having a height?Android - 为什么 TextView 显示为具有高度?
【发布时间】:2011-12-30 21:25:26
【问题描述】:

我在这里遇到了一个奇怪的问题。基本上我有一个没有默认设置文本的 TextView。我原以为它的高度为 0,因为它没有内容,但它上面和下面的元素之间似乎存在间隙。如果我在 XML 中将高度设置为 0,然后尝试通过 Java 代码更改它,那么它不会重置高度。

如果内容为空白,如何将高度设置为 0,然后允许以编程方式对其进行更改?

这是我的代码:

<TextView 
    android:gravity="center_horizontal|center_vertical"
    android:id="@+id/connectionStatus"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:textSize="18px"
    android:textStyle="bold">
</TextView>

Java 代码是这样的:

    private void getConnectionStatus()
{
    if (hasConnection() == true)
    {
        //do something
    }
    else
    {
        connectionStatus.setHeight(48);
        connectionStatus.setText("No Internet Access");
    }   
}

【问题讨论】:

  • 为什么要将高度设置为 0?将高度保留为wrap_content 并隐藏视图。
  • 编辑了标签(删除了'connection'标签,并添加了'view'和'visibility'标签)

标签: android view height visibility


【解决方案1】:

在 xml 布局中使用“消失”的可见性。然后在Java代码中调用connectionStatus.setVisibility(View.VISIBLE);

【讨论】:

  • 同意。设置可见性是隐藏/显示视图的正确方法。
【解决方案2】:

即使没有内容,组件仍然可以显示自己。例如,可以显示边框或其可视区域。为了让它根本不显示,您需要使用setVisibility(View.GONE)

【讨论】:

    【解决方案3】:

    我经常想知道这种行为是否直观。如果您想要一个在文本为空时没有高度的TextView,您可以制作一个:

    import android.content.Context;
    import android.support.annotation.Nullable;
    import android.text.TextUtils;
    import android.util.AttributeSet;
    
    public class NoHeightWhenEmptyTextView extends android.support.v7.widget.AppCompatTextView {
    
        public NoHeightWhenEmptyTextView(Context context) {
            super(context);
        }
    
        public NoHeightWhenEmptyTextView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        public NoHeightWhenEmptyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int newHeightMeasureSpec = heightMeasureSpec;
            if (TextUtils.isEmpty(getText())) {
                newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.EXACTLY);
            }
            super.onMeasure(widthMeasureSpec, newHeightMeasureSpec);
        }
    
        @Override
        public void setText(CharSequence text, BufferType type) {
            super.setText(text, type);
            // ConstraintLayout totally ignores the new measured height after non-empty text is set.
            // A second call to requestLayout appears to work around the problem :(
            requestLayout();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 2019-05-06
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      相关资源
      最近更新 更多