Change xml selector values from java code

前端 未结 2 2046
清歌不尽
清歌不尽 2020-12-16 06:16

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条回答
  •  伪装坚强ぢ
    2020-12-16 06:40

    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
    

提交回复
热议问题