Android : How to update the selector(StateListDrawable) programmatically

后端 未结 5 2125
耶瑟儿~
耶瑟儿~ 2020-11-28 06:05

I want to update the selector for a button programmatically.

I can do this with the xml file which is given below



        
5条回答
  •  被撕碎了的回忆
    2020-11-28 06:06

    I am going to answer your question "How to update the selector for a BUTTON programmatically?" by proposing to switch a button for a LinearLayout with embedded ImageView and TextView. There are a number of benefits to doing this, especially if you will later decide to customize your views. There is no loss of functionality resulting from this switch. You will still be able to attach same event listeners you can attach to a button, but will be able to avoid the buttons/tabs styling nightmares. Here is a relevant code from the layout.xml

        
            
            
         
    

    Next, I have a selector file called custom_image.xml located in the drawable folder. Here is the content of the selector file

    
    
        
        
        
    
    

    The three source image files (disabled_img.png, unselected_img.png, selected_img.png) are also located in the drawable folder.

    Now back to your Java code. There is no need for the funky StateListDrawable garbage for many reasons. First, it just looks ugly, and is hard to maintain. But most importantly it goes against the principles of keeping your logic separate from your presentation. If you are managing your drawable resources in Java code, you know you are doing something fundametally wrong.

    Here is what I am proposing instead. Whenever you want your button to be selected, you just pop this one-liner in there:

    ((LinearLayout)findViewById(R.id.button)).setSelected(true);
    

    Or whenever you want the button to be in the disabled state, here is another one-liner:

    ((ImageView)findViewById(R.id.background)).setEnabled(false);
    

    Please notice that in this last example I am specifying the disabled state on the ImageView inside the LinearLayout. For some reason whenever you change the enabled / disabled state of the LinearLayout, the selector is not being triggered. It works fine when you do it on the ImageView instead.

提交回复
热议问题