Android定制按钮;更改文字颜色
-
11-10-2019 - |
题
我制作了一个按钮,可以改变不同状态的背景,这样:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_location_pressed" /> <!-- pressed -->
<item android:state_focused="true" android:drawable="@drawable/btn_location_pressed"/> <!-- focused -->
<item android:drawable="@drawable/btn_location"/> <!-- default -->
这里的问题在于,我也试图像可绘制的那样更改文本彩色,但我无法做到。我已经尝试了Android:TextColor和Android:颜色,但第一个不起作用,而几秒钟会改变我的背景。
下一个代码是我布局的一部分。关于文本颜色,它仅适用于正常状态文本颜色,因此在按下时不会将其更改为白色
<Button android:id="@+id/location_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:background="@drawable/location"
android:textSize="15sp"
android:textColor="@color/location_color"
android:textColorHighlight="#FFFFFF"
/>
有人有线索吗?
解决方案
例如,像您为背景一样为您的按钮创建状态颜色,例如:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Focused and not pressed -->
<item android:state_focused="true"
android:state_pressed="false"
android:color="#ffffff" />
<!-- Focused and pressed -->
<item android:state_focused="true"
android:state_pressed="true"
android:color="#000000" />
<!-- Unfocused and pressed -->
<item android:state_focused="false"
android:state_pressed="true"
android:color="#000000" />
<!-- Default color -->
<item android:color="#ffffff" />
</selector>
将XML放在res/drawable文件夹的文件中,即res/drawable/button_text_color.xml。然后将可绘制的可绘制设置为文本颜色:
android:textColor="@drawable/button_text_color"
其他提示
另一种做到这一点的方法是在您的班上:
import android.graphics.Color; // add to top of class
Button btn = (Button)findViewById(R.id.btn);
// set button text colour to be blue
btn.setTextColor(Color.parseColor("blue"));
// set button text colour to be red
btn.setTextColor(Color.parseColor("#FF0000"));
// set button text color to be a color from your resources (could be strings.xml)
btn.setTextColor(getResources().getColor(R.color.yourColor));
// set button background colour to be green
btn.setBackgroundColor(Color.GREEN);
好的,非常简单,第一个转到1。res-valuse和open colors.xml 2.定义文本的副本1,例如#ff4081,然后更改名称,例如我更改为white并更改其值,例如我更改为#ffffff for像这样的白色价值
<color name="White">#FFFFFF</color>
然后在您的按钮内添加此行
b3.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.White));
OK B3是我的按钮的名称,因此,如果您更改不同的颜色,则更改其他按钮的名称,所有其他按钮都将相同,然后将白色更改为颜色名称,但首先您将其定义为颜色。 XML就像我在Pont 2中解释的那样
更改按钮的文字颜色
因为现在已弃用此方法
button.setTextColor(getResources().getColor(R.color.your_color));
我使用以下内容:
button.setTextColor(ContextCompat.getColor(mContext, R.color.your_color));
利用 getColorStateList
像这样
setTextColor(resources.getColorStateList(R.color.button_states_color))
代替 getColor
setTextColor(resources.getColor(R.color.button_states_color))
不隶属于 StackOverflow