6

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?

1
  • for which control you want to set drawable resource. e.g. Button or textview Commented Jun 28, 2012 at 10:36

2 Answers 2

25

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
Sign up to request clarification or add additional context in comments.

4 Comments

imageView? do i need to set up one within my layout?
yes as your need create dynamically or add an Imageview to Xml layout
@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!!! :)
needed to add the negative value for each state to make it work. Thanks!!
3

You can set button drawable from java like

    btnSettings.setBackgroundResource(R.drawable.ic_launcher);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.