简体   繁体   English

如何在按下按钮时动态更改图片并保存该图片的状态

[英]How to change a picture dynamically when a button is pressed and save the state of that image

Good morning people. 大家早上好。

I have a problem where I need to change an image of an imageView when the Button is pressed and when it is pressed again change to the image that was previously. 我有一个问题,我需要在按下Button时更改imageView的图像,并在再次按下Button时更改为先前的图像。 I even managed to do this through the setBackgroundResource , the problem is when I close the application or exit that particular Activity and return to it the image is back to the one that was in android: background from the beginning. 我什至设法通过setBackgroundResource做到了这一点,问题是当我关闭应用程序或退出该特定的Activity并返回到图像时,图像从一开始就回到了android: background

Can someone help me? 有人能帮我吗?

PS I'm using the translator, sorry if I have something spelled wrong. PS:我正在使用翻译器,如果我拼写错误,对不起。

Xml code XML代码

<Button
android:id="@+id/buttonLigarDesligar"
android:padding="10dp"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/icone_ligar"/>

<ImageView
android:id="@+id/imgStatus"
android:padding="10dp"
android:background="@drawable/icone_vermelho"
android:layout_width="40dp"
android:layout_height="40dp"/>

Java code Java代码

buttonLigarDesligar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int status = 0;

        if (status == 0){ 
            imgStatus.setBackgroundResource(R.drawable.ic_on);
            status = 1;
        }else{
            imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
            status = 0;                   
        }
    }
});

} }

Try doing it this way. 尝试以这种方式进行。 You need to save the state yourself. 您需要自己保存状态。

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

String status = preferences.getInt("status", 0);

In your onClicklistener 在您的onClicklistener中

if (status == 0){ 
        imgStatus.setBackgroundResource(R.drawable.ic_on);
        editor.putInt("status", 1);
    }else{
        imgStatus.setBackgroundResource(R.drawable.icone_vermelho);
        editor.putInt("status", 0);            
    }
   editor.apply();
}

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

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