3

How to change color text in button when the user touches this button?

Here is my shape.xml code:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >


 <item android:state_pressed="true" >
<shape android:shape="rectangle">
  <gradient android:startColor="#ffcc33" 
    android:endColor="#ffcc33"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

  <item android:state_focused="true" >
<shape android:shape="rectangle">
  <gradient android:startColor="#ffcc33" 
    android:endColor="#ffcc33"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

  <item >
<shape android:shape="rectangle">
  <gradient android:startColor="#333333" 
    android:endColor="#333333"
    android:angle="270" />
  <corners android:radius="4dp" />
  <stroke android:width="2px" android:color="#FFFFFF" />
</shape>
</item>

</selector>
CJBS
  • 15,147
  • 6
  • 86
  • 135
Mateusz Ryndak
  • 87
  • 2
  • 6
  • 13

2 Answers2

12

Use color selector, something like this

src/color/button_text.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true" android:color="#000000" /> 
     <item android:state_focused="true" android:color="#000000" />
     <item android:color="#FFFFFF" />
 </selector>

Then in the button you do this

<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/text"
   android:textColor="@color/button_text" />
Olayinka
  • 2,813
  • 2
  • 25
  • 43
0

Your probably going to want to do other stuff once you have pressed the button so why not just create a normal button and set its background to your shape and then in java create an onTouch event for the button

    Button.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                // do other stuff     
                Button.setTextColor(Color.parseColor("#000000"));
            }
            else if (event.getAction() == MotionEvent.ACTION_UP)
            {
                Button.setTextColor(Color.parseColor("#FFFFFF"));
            }
            return false;
        }
    });
Rob85
  • 1,719
  • 1
  • 23
  • 46