I am trying to create a universal image selector for multiple buttons. Is there an option to change the xml's "android:drawable" resource from java code?
use StateListDrawable for seeting 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
You can set button drawable from java like
btnSettings.setBackgroundResource(R.drawable.ic_launcher);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With