Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Button state changed event

Tags:

android

Some XML attributes of buttons (such as background, textColor, etc) can be defined with color or drawable state List like this:

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

When view state changes (pressed/unpressed, for example), corresponding color is changed automatically.

How can I prograqmmatically handle some kind of stateChangedEvent to perform more complicated layout change, than just changing a color (for example, change font size or set another text)?

like image 478
PVoLan Avatar asked Dec 22 '22 04:12

PVoLan


2 Answers

For focus changes and touch events you can register listeners by setOnFocusChangeListener and setOnTouchListener. And changes about disabled/enabled states you can perform directly after changing your button state.

like image 116
muffinmad Avatar answered Dec 23 '22 17:12

muffinmad


// use the selector method to pass your button and image // you can use color also

b1=(Button)findViewById(R.id.button1);

//      b2=(Button)findViewById(R.id.button2);


        selector(b1, R.drawable.image_1_2, R.drawable.image_1);
      //  selector(b2, R.drawable.image_2_2, R.drawable.image_2);


    }

    public void selector(Button b,int pressed_image,int normal_image )
    {
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[] {android.R.attr.state_pressed},
            getResources().getDrawable(pressed_image));         
       states.addState(new int[] { },
            getResources().getDrawable(normal_image));      
        b.setBackgroundDrawable(states);
    }
like image 29
Padma Kumar Avatar answered Dec 23 '22 19:12

Padma Kumar