简体   繁体   English

使用切换按钮更改图像

[英]Change Image with toggle button

I am new to Android developing. 我是Android开发的新手。 I managed to do a task to change an image for clicking two different buttons. 我设法完成了一个任务,以通过单击两个不同的按钮来更改图像。

My MainActivity.java : 我的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 ? 我想使代码保持非常简单,并使用切换按钮尝试过的一个按钮进行修改,但是我可以使用lightBox识别onClick,但应该在哪里识别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 尝试使用此逻辑仅用一个按钮切换图像...在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.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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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