-2

I am doing an Android application in which I have placed an image button. I have given a default image source. When I click the image it should change the image source to another and if I press the image again I should get the default image back.

It's like toggling between two images. But I don't want to use toggleButton due to requirements of my app.

halfer
  • 19,824
  • 17
  • 99
  • 186
Karthik
  • 1,088
  • 6
  • 17

2 Answers2

2

If you don't want anything to do with toggle, you would have to keep a counter.

XML:

<android.support.v7.widget.AppCompatImageButton
        android:id="@+id/button"
        android:layout_width="10dp"
        android:layout_height="match_parent"
        android:src="@mipmap/original"
        android:background="@color/original"/>

Activity:

public class Activity extends AppCompatActivity {

    int clickcounter = 0;        

    @Bind(R.id.button)
    ImageButton Button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Butter Knife
        ButterKnife.bind(this);

        //Hook up the OnClick Listener
        feedButton.setOnClickListener(feedButtonHandler);

    }

View.OnClickListener feedButtonHandler = new View.OnClickListener() {
    public void onClick(View v) {
        clickcounter = clickcounter + 1;
        if (clickcounter % 2 == 1) {
        // setImageResource is the method for setting imagebutton's src in xml
        Button.setImageResource(R.mipmap.new);
        // setBackgroundResource is the method for setting imagebutton's background in xml
        Button.setBackgroundResource(R.color.new);
        }

        if (clickcounter % 2 == 0) {
        Button.setImageResource(R.mipmap.original);
        Button.setBackgroundResource(R.color.original);
        }
    };
}

But toggle is a simpler way to do it.

seibeki
  • 33
  • 4
0
ImageButton:

<ImageButton
    android:id="@+id/imagebutton"
    android:layout_width="250dp"
    android:layout_height="100dp" 
    android:background="@drawable/img_btn_selector"/>

img_btn_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_selected="true" android:drawable="@drawable/img_selected" />
    <item android:drawable="@drawable/img_un_selected" />    
</selector>

Activity:

imgBtn.setOnClickListener(new OnClickListener() {

       public void onClick(View button) {
           if (button.isSelected()){
               button.setSelected(false); 
           } else {
               button.setSelected(true);
           }
       }
   }); 
Logic
  • 2,230
  • 2
  • 24
  • 41