Change xml selector values from java code

2020-02-09 14:32发布

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?

标签: android
2条回答
可以哭但决不认输i
2楼-- · 2020-02-09 14:42

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
查看更多
闹够了就滚
3楼-- · 2020-02-09 14:47

You can set button drawable from java like

    btnSettings.setBackgroundResource(R.drawable.ic_launcher);
查看更多
登录 后发表回答