Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change xml selector values from java code

Tags:

android

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?

like image 554
TalMihr Avatar asked Jun 28 '12 10:06

TalMihr


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
like image 113
ρяσѕρєя K Avatar answered Oct 11 '22 12:10

ρяσѕρєя K


You can set button drawable from java like

    btnSettings.setBackgroundResource(R.drawable.ic_launcher);
like image 36
Nirali Avatar answered Oct 11 '22 13:10

Nirali