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?
2 Answers
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
4 Comments
TalMihr
imageView? do i need to set up one within my layout?
ρяσѕρєя K
yes as your need create dynamically or add an Imageview to Xml layout
ρяσѕρєя K
@user1185841 : you can try to search on google how we create a dynamic ImageView in android.if this answer help u in solving your problem then mark it as answer.Thanks friend!!! :)
TalMihr
needed to add the negative value for each state to make it work. Thanks!!