1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Android Button按钮点击变换字体颜色

Android Button按钮点击变换字体颜色

时间:2024-01-31 22:44:47

相关推荐

Android Button按钮点击变换字体颜色

一、在xml中修改颜色

1、首先贴上/res/values/color色值

<?xml version="1.0" encoding="utf-8"?><resources><color name="black">#000000</color><color name="white">#ffffff</color></resources>

2、贴上/res/drawable/text_color_selector.xml颜色选择器

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="/apk/res/android"><item android:color="@color/black" android:state_pressed="true"></item><item android:color="@color/white"></item></selector>

3、贴上布局/res/layout/activity_main.xml代码

<RelativeLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.testcolor.MainActivity" ><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@drawable/text_color_selector"android:text="@string/text_click_state" /><!-- @string/text_click_state --><!-- <string name="text_click_state">字体点击效果</string> --></RelativeLayout>

二、在代码中修改颜色

我们首先添加一个ColorStateList资源XML文件,XML文件保存在res/color/button_text.xml:

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><selector xmlns:android="/apk/res/android"><item android:state_pressed="true" android:color="#ffff0000"/> <!-- pressed --><item android:state_focused="true" android:color="#ff0000ff"/> <!-- focused --><item android:color="#ff000000"/> <!-- default --></selector></span>

<span style="font-size:14px;">Button btn=(Button)findViewById(R.id.btn); Resources resource=(Resources)getBaseContext().getResources(); ColorStateList csl=(ColorStateList)resource.getColorStateList(R.color.button_text); if(csl!=null){ btn.setTextColor(color_state_list);//设置按钮文字颜色 }</span>

或者可以这样:

<span style="font-size:14px;">XmlResourceParser xpp=Resources.getSystem().getXml(R.color.button_text); try { ColorStateList csl= ColorStateList.createFromXml(getResources(),xpp); btn.setTextColor(csl); } catch (Exception e) { // TODO: handle exception } </span>

运行之后点击按钮就可以看到字体的颜色变化了

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。