简体   繁体   中英

Change Image with toggle button

I am new to Android developing. I managed to do a task to change an image for clicking two different buttons.

My MainActivity.java :

package com.example.sandorhorvath.imageviewchange;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {


    public void lightBox(View view) {
       ImageView image = (ImageView) findViewById(R.id.imageView);
       image.setImageResource(R.drawable.kawa2);
    }

    public void lightBox1(View view) {
        ImageView image = (ImageView) findViewById(R.id.imageView);
        image.setImageResource(R.drawable.kawa1);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

I want to keep the code really simple and make the same with one button I tried with toggle but I can identify the onClick with lightBox but where should I identify the lightBox2 ? I can turn on the function but I don't find the off function value.

Try this logic for toggling image with only one button ...write this in click func

boolean check = false;

public void lightBox(View view) {

 if(check) {
 image
.setImageResource(R.drawable.kawa1                                          ); 
 check = false;}
else {
 image
.setImageResource(R.drawable.kawa2                                        ); 
 check = true;}

 }

Working like a charm a little modification added to the code the image had to be defined.

boolean check = false;

public void lightBox(View view) {
    ImageView image = (ImageView) findViewById(R.id.imageView);

    if(check) {
        image.setImageResource(R.drawable.kawa1);
        check = false;
    } else {
        image.setImageResource(R.drawable.kawa2);
        check = true;
    }

 }

Thank you for your help! The logic is perfect!

You can use android.support.design.widget.CheckableImageButton from the support design library like this:

         <android.support.design.widget.CheckableImageButton
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:textOn="@null"
             android:textOff="@null"
             android:background="@null"
             android:src="@drawable/your_image"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM