我正在尝试为多个按钮创建通用图像选择器。
是否可以从Java代码更改xml的“android:drawable”资源?
最佳答案
使用StateListDrawable通过代码将选择器设置为:
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