Changing xml selector values โ€‹โ€‹from java code

I am trying to create a universal image selector for several buttons. Is it possible to change the xml resource "android: drawable" from java code?

+5
source share
2 answers

use StateListDrawable to select the selector by code as:

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
    getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},
    getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },
    getResources().getDrawable(R.drawable.normal));

imageView.setImageDrawable(states);  //YOUR IMAGE HERE
//AND FOR BUTTON
 button.setBackgroundDrawable(states);//FOR BUTTON
+25
source

You can set the button using java, for example

    btnSettings.setBackgroundResource(R.drawable.ic_launcher);
+3
source

All Articles