ImageButton onClick change color

I create an ImageButton as follows:

<ImageButton android:id="@+id/one" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="0.333" android:adjustViewBounds="true" android:background="@null" android:contentDescription="@string/description_image_button_one" android:scaleType="fitEnd" android:src="@drawable/dialpad_1" /> 

I would like to implement a way to click a button or change color when pressed / pressed to determine that it was pressed. I know that I can refer to the background as being portable with the state_pressed selector to a specific color. I am trying to avoid creating a separate XML file for each button in drawable. What is the best way to do this without creating all these additional XML files?

+6
source share
3 answers

You need to create custom selectors for the background of the buttons.

This file will live in your XML folder and look something like this (each element describes the background of the button in different selected states):

The file will be called: res / drawable / my_custom_selector.xml

 <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/blue_button_on" android:state_focused="true" android:state_pressed="true"/> <item android:drawable="@drawable/blue_button_on" android:state_focused="false" android:state_pressed="true"/> <item android:drawable="@drawable/blue_button_off" android:state_focused="true" android:state_pressed="false"/> <item android:drawable="@drawable/blue_button_off" android:state_focused="false" android:state_pressed="false"/> </selector> 

Then, to apply this background to your ImageView (or any view), just set it as a background:

  <ImageButton android:id="@+id/one" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="0.333" android:adjustViewBounds="true" android:background="@drawable/my_custom_selector" android:contentDescription="@string/description_image_button_one" android:scaleType="fitEnd" android:src="@drawable/dialpad_1" /> 
+10
source

The XML files you are trying to avoid are an easy way to achieve what you want. Another way would be to do this using code in onClickListener , which, in my opinion, is a task that requires much more work.

+1
source

You must use XML files or do nothing. Android provides the default color for the pressed button.

0
source

Source: https://habr.com/ru/post/950624/


All Articles