我遇到了一个奇怪的问题。基本上我有一个没有默认文本的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");
}
}
在xml布局中使用可见性"gone"。然后在Java代码中调用connectionStatus.setVisibility(View.VISIBLE);
组件即使没有内容也可以显示自己。例如,可以显示边框或其可见区域。为了使它不显示,你需要使用setVisibility(View.GONE)
。
我经常怀疑这种行为是否直观。如果你想要一个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();
}
}