Android - 为什么 TextView 显示为有高度?
我这里有一个奇怪的问题。基本上我有一个没有默认设置文本的 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");
}
}
I've got an odd problem here. Basically I have a TextView with no default set text. I would've expected it to have a height of 0 since it hsas no content but there seems to be a gap between the elements above and below it. If I set the height to 0 in the XML and then try and change it through Java code then it does not reset the height.
How do I set the height to be 0 if the content is blank but then allow it to be changed programmatically?
Here is the code that 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 the Java code is this:
private void getConnectionStatus()
{
if (hasConnection() == true)
{
//do something
}
else
{
connectionStatus.setHeight(48);
connectionStatus.setText("No Internet Access");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 xml 布局内部“消失”的可见性。然后在Java代码中调用
connectionStatus.setVisibility(View.VISIBLE);
Use visibility "gone" inside of the xml layout. Then in the Java code call
connectionStatus.setVisibility(View.VISIBLE);
即使组件没有内容,它们仍可能会显示自身。例如,可以显示边框或其可视区域。为了使其根本不显示,您需要使用
setVisibility(View.GONE)
。Components may still display themselves even if they don't have content. For example, the may display a border or their viewable area. In order to make it not show up at all you need to use
setVisibility(View.GONE)
.我经常想知道这种行为是否直观。如果您想要一个在文本为空时没有高度的
TextView
,您可以制作一个:I've often wondered if this behaviour is intuitive. If you want a
TextView
that has no height when the text is empty you can make one: