Android自定义button; 改变文字颜色

我做了一个button,这样可以在不同状态下修改背景:

<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 --> 

这里的问题是,我也试图改变textColor,因为我用可绘制的,但我不能。 我已经尝试过android:textColor和android:color,但是第一个不工作,而秒改变我的背景。

下一个代码是我的布局的一部分。 关于文字颜色,它只适用于正常状态的文字颜色,因此在按下时不会将其改为白色

 <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" /> 

有人有线索吗?

为您的button创build一个有状态的颜色,就像您为背景所做的一样,例如:

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:state_pressed="false" android:color="#ffffff" /> <item android:state_focused="true" android:state_pressed="true" android:color="#000000" /> <item android:state_focused="false" android:state_pressed="true" android:color="#000000" /> <item android:color="#ffffff" /> </selector> 

将XML放在res / drawable文件夹中的一个文件中,例如res / drawable / button_text_color.xml。 然后只需将drawable设置为文本颜色即可:

 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并打开colors.xml 2.复制定义的文本1他们的例如#FF4081和更改名称例如我改成白色,并改变它的值例如我改为#FFFFFF for像这样的白色值

 <color name="White">#FFFFFF</color> 

然后在你的button里添加这一行

  b3.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.White)); 

确定b3是我的button的名称,所以如果你改变了不同的颜色,然后将白色改为你的颜色的名称,但是你首先已经用颜色定义了颜色,那么所有其他button的名称都改变了。 xml就像我在pont 2中解释的那样

更改button的文本颜色

因为此方法现在已被弃用

 button.setTextColor(getResources().getColor(R.color.your_color)); 

我使用以下内容:

 button.setTextColor(ContextCompat.getColor(mContext, R.color.your_color));