2

I need to change Button Color(normal/pressed) using Selector

res/color/test_color_button.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/button_focused"/>
<item android:state_pressed="false" android:color="@color/button_font"/>
<item android:color="@color/button_font"/>
</selector>

in code class MyButton (its extended from class Button) and I used following code to set text color

 //at Constructor 
 this.setTextColor(getResources().getColor(R.color.text_color_button));

But my problem is ,Button alwas shows default color

Ravi
  • 34,851
  • 21
  • 122
  • 183
Nooh
  • 1,548
  • 13
  • 21

3 Answers3

2

You need to create a ColorStateList object

XmlResourceParser parser = getResources().getXml(R.color.test_color_button);
ColorStateList colorStateList = ColorStateList.createFromXml(getResources(), parser);
this.setTextColor(colorStateList);
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

try to set the selector to the background like this:

<Button
   android:id="@+id/button1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/button_bg" />
Kaushik
  • 6,150
  • 5
  • 39
  • 54
balaji koduri
  • 1,321
  • 9
  • 25
  • i know that,i want to set style(font,color,background etc) to all buttons,so i created own button programmatically.thanks for your answer – Nooh Oct 29 '14 at 09:32
0

Why changing colors,lets do a complete new attractive thing.... I am sure you will like it

  1. Create an xml file in your drawable folder named as button_bg.xml like the following

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:drawable="@drawable/button_pressed" android:state_pressed="true" />
    
        <item android:drawable="@drawable/button" />
    
    </selector>
    

where button_pressed and button are the images which you want to show on button pressed and normal state of button

  1. Set the background of the button as button_bg.xml like the following

    <Button
       android:id="@+id/button1"
       android:layout_width="250dp"
       android:layout_height="70dp"
       android:layout_marginLeft="360dp"
       android:layout_marginTop="520dp"
       android:background="@drawable/button_bg"  <!--like this-->
       android:text="Login"
       android:textColor="#ffffff"
       android:textSize="30dp" />
    

and enjoy!

Kaushik
  • 6,150
  • 5
  • 39
  • 54
nobalG
  • 4,544
  • 3
  • 34
  • 72