Java Android 开发切换 TextView 可见性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6558364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:44:09  来源:igfitidea点击:

Android development toggling TextView visibility

javaandroid

提问by Yuval

Im having some trouble with setting textview to invisible/visible.

我在将 textview 设置为不可见/可见时遇到了一些麻烦。

basicly i want this to happen when an on/off button has been clicked.

基本上我希望在单击开/关按钮时发生这种情况。

what i did is kind of like

我所做的有点像

textview.setVisibility(TextView.VISIBLE);
textview.setVisibility(TextView.INVISIBLE);

when i try executing this the emultor says that the app has stopped unexcpetedly

当我尝试执行此操作时,模拟器说该应用程序已意外停止

采纳答案by Ethan

Are you building this from XML or programmatically?

您是从 XML 还是以编程方式构建它?

I would make it with an XML file then when the Activity runs change the property. Be sure to use setContentView(R.layout.main);before you try to get the TextView with findViewById(...).

我会用一个 XML 文件制作它,然后当 Activity 运行时更改属性。setContentView(R.layout.main);在尝试使用.TextView 获取 TextView 之前,请务必使用findViewById(...)

Call .setVisibility(View.GONE);on the TextView to hide it.

调用.setVisibility(View.GONE);TextView 以隐藏它。

Call .setVisibility(View.VISIBLE);to on the TextView to show it.

.setVisibility(View.VISIBLE);在 TextView 上调用to 以显示它。

I have an example that does something like this. You can see the code here: https://github.com/ethankhall/Morse-Messenger/blob/master/src/com/kopysoft/MorseMessenger/Translate.java

我有一个例子可以做这样的事情。您可以在此处查看代码:https: //github.com/ethankhall/Morse-Messenger/blob/master/src/com/kopysoft/MorseMessenger/Translate.java

回答by mibollma

Read about DDMS and logcat to obtain a stacktrace and to see what the problem is: http://developer.android.com/guide/developing/debugging/debugging-projects.html

阅读有关 DDMS 和 logcat 以获取堆栈跟踪并查看问题所在:http: //developer.android.com/guide/developing/debugging/debugging-projects.html

This is what you are looking for: enter image description here

这就是你要找的: 在此处输入图片说明

回答by Todd Davies

Without more code or a stack trace, it's hard to say, but it sounds like you haven't initialized the text view. Here's how to do it:

没有更多代码或堆栈跟踪,这很难说,但听起来您还没有初始化文本视图。这是如何做到的:

TextView myTextView = (TextView) findViewById(R.id.tv_text);

Where 'tv_text' is the id of the textview as defined in the xml layout file.

其中 'tv_text' 是 xml 布局文件中定义的 textview 的 id。

Hope that helped!

希望有所帮助!