Setting drawable state programatically based on input

482 Views Asked by At

I have custom drawables that I am using in place of buttons. For example, camButton opens the native camera so the user can take a picture.

camButton has resources provided so the drawable can be either white or green. This is how camButton should behave:

1) The default, no-input state is white.

2) The state with input provided is green. i.e. If the user has successfully taken a picture and not deleted it, the drawable is green to indicate this.

3) Pressing the button when it is white should turn it green until the user releases the button.

4) Pressing the button when it is green does nothing.

Below is a selector to test something similar to this. But this selector only changes the color of the button when it is pressed. It addresses #1 and #3 above, but not #2 or #4.

cam_selector.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- green --> <item android:drawable="@drawable/cam_pressed" android:state_pressed="true"/> 
    <!-- green --> <item android:drawable="@drawable/cam_pressed" android:state_long_pressable="true"/> 
    <!-- white --> <item android:drawable="@drawable/cam_normal"/> 
</selector>

This is how the selector is implemented in my main layout:

<Button
    android:id="@+id/camButton"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:background="@drawable/cam_selector"/>

In my app, I test to see if there is input provided using booleans.

Question: How can I set the state of camButton to @drawable/cam_pressed based on the booleans in my code (or another way)?

Please let me know if I am being unclear, or if you need additional information. Any advice is appreciated. Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER
Button button = (Button) findViewById(R.id.camButton);      
if(camPressed){
    button.setBackground(getResources().getDrawable(R.drawable.cam_pressed))
 } else{
     //other stuff
 }