Change xml selector values from java code

前端 未结 2 2042
清歌不尽
清歌不尽 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
    
    0 讨论(0)
  • 2020-12-16 06:49

    You can set button drawable from java like

        btnSettings.setBackgroundResource(R.drawable.ic_launcher);
    
    0 讨论(0)
提交回复
热议问题