Android 如何在按下或聚焦时使按钮文本变为粗体
我想在突出显示或按下按钮时将按钮内的文本更改为粗体。我目前使用 xml 文件来定义按钮,并使用 XML 来更改按下时的外观,但我想在不使用图像的情况下执行此操作。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="@drawable/reset_hover" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/reset_hover" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/reset_hover" />
<item android:drawable="@drawable/reset" />
</selector>
我尝试使用类似以下的内容,但似乎从未被调用过。
final Button btn_reset = (Button) findViewById(R.id.btn_reset);
btn_reset.setOnClickListener(this);
btn_reset.setOn(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){btn_reset.setTypeface(null, Typeface.BOLD);}
else{btn_reset.setTypeface(null, Typeface.NORMAL);}
}
});
I want to change the text inside a button to be bold when the button is highlighted or pressed. I currently use a xml file to define the button and use the XML to change how it looks when pressed but I would like to do this without using an image.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="@drawable/reset_hover" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/reset_hover" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/reset_hover" />
<item android:drawable="@drawable/reset" />
</selector>
I tried using something like the following, but it doesn't seem to ever get called.
final Button btn_reset = (Button) findViewById(R.id.btn_reset);
btn_reset.setOnClickListener(this);
btn_reset.setOn(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){btn_reset.setTypeface(null, Typeface.BOLD);}
else{btn_reset.setTypeface(null, Typeface.NORMAL);}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试将粗体代码放入按钮的单击事件中:
You could try putting the bold code inside the click event for the button:
注意力!请参阅下面的更新
您可以创建自己的 style.xml,在其中定义文本样式。您可以在选择器中引用样式。
style.xml
在您的选择器中
更新 2020:我的答案已有 10 多年历史了。它不再起作用了!
Attention! See update below
You could create your own style.xml in which you define the text style. In your selector you can reference to the style.
style.xml
And in your selector
Update 2020: My answer is more than 10 years old. It doesn´t work anymore!
选择器中不允许使用样式。 参考
要将文本设为粗体,请使用以下代码:
Styles are not allowed in selectors. Reference
And to make the text bold, use this code: