Android Why is the TextView shown as having a height?

I have a strange problem here. Basically I have a TextView without standard text. I would expect it to have a height of 0, as it has no content, but there seems to be a space between the elements above and below it. If I set the height to 0 in XML format, and then try to change it using Java code, then this will not reset the height.

How to set the height to 0 if the content is empty and then allow its programmatic change?

Here is the code I have:

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

and Java code:

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

Use visibility "gone" inside the xml layout. Then, in a Java code call, connectionStatus.setVisibility(View.VISIBLE);

+6
source

Components may be displayed even if they do not have content. For example, a border or scope may be displayed. To prevent it from appearing at all, you need to use setVisibility(View.GONE) .

+2
source

I often wondered if this behavior is intuitive. If you want the TextView not have height when the text is empty, you can do the following:

 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(); } } 
0
source

Source: https://habr.com/ru/post/1381588/


All Articles