如何更改 Android 中 Button 小部件的文本?
如何在代码中而不是 XML 文件中更改 Android Button 小部件的文本?
How can I change the text of an Android Button widget within code and not the XML file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
setText()
方法。示例:另外,作为参考, Button 扩展了 TextView,因此您可以使用
setText()
就像普通的 TextView 一样。You can use the
setText()
method. Example:Also, just as a point of reference, Button extends TextView, hence why you can use
setText()
just like with an ordinary TextView.我能够像这样更改按钮的文本:
I was able to change the button's text like this:
这很容易
This is very easy
我的layout.xml中有一个按钮,它被定义为视图,如下所示:
我无法更改其上的文本,直到我也将其定义为按钮:
当我需要更改文本时,我使用了
bButton.setText("Some Text");
当我想改变视图时,我使用了vButton。
效果很好!
I had a button in my layout.xml that was defined as a View as in:
I was not able to change the text on it until I also defined it as a button:
When I needed to change the text, I used the
bButton.setText("Some Text");
and when I wanted to alter the view, I used thevButton.
Worked great!
使用java进行交换。 setText = "...",对于java类来说还有很多方法可以实现。
use the exchange using java. setText = "...", for class java there are many more methods for implementation.
这可能偏离主题,但对于那些正在努力如何准确更改按钮文本字体的人(这是我的情况,Skatephone 的答案帮助了我),我是这样做的(如果您在设计模式中制作了按钮):
首先,我们需要将按钮的字符串名称从 xml“转换”(这是一种糟糕的解释方式,但很简单)到 java,因此我们将上述代码粘贴到 MainActivity.java 中
my_layout
必须替换为按钮所在的 xml 文件Counter
必须替换为按钮的 ID 名称 ("@+ id/ButtonName"
)如果您想更改按钮文本,只需插入文本代替
“在此处设置按钮文本”
现在您已从 xml“转换”为 java,您可以为 TextView 设置 Typeface 方法。将以下代码准确粘贴到上面描述的前一个代码的下方
,其中您放置按钮的 ID 名称(如之前的代码)的
text_your_text_view_id
位置以及MyFontName.ttf
你输入你想要的字体This may be off topic, but for those who are struggling on how to exactly change also the font of the button text (that was my case and Skatephone's answer helped me) here's how I did it (if you made buttons ind design mode):
First we need to have the button's string name "converted" (it's a foul way to explain, but straightforward) into java from the xml, and so we paste the aforementioned code into our MainActivity.java
my_layout
has to be substituted with the xml file where your buttons areCounter
has to be substituted with the id name of your button ("@+id/ButtonName"
)if you want to change the button text just insert the text in place of
"Set button text here"
Now that you "converted" from xml to java, you can set a Typeface method for TextView. Paste the following code exactly under the previous one just described above
where in place of
text_your_text_view_id
you put your button's id name (like as previous code) and in place ofMyFontName.ttf
you put your desired font//文本按钮:
//颜色文本按钮:
//背景按钮
//文本大小按钮
//text button:
// color text button:
// background button
// text size button