首页 > 解决方案 > 如何在按下按钮时动态更改图片并保存该图像的状态

问题描述

大家早上好。

我有一个问题,我需要在按下时更改图像,imageViewButton再次按下时更改为以前的图像。我什至设法通过 来做到这一点setBackgroundResource,问题是当我关闭应用程序或退出该应用程序Activity并返回到它时,图像又回到了android: background从一开始就存在的那个。

有人能帮我吗?

PS我正在使用翻译器,如果我拼写错误,请见谅。

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 代码

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;                   
        }
    }
});

}

标签: javaandroidandroid-layout

解决方案


尝试这样做。您需要自己保存状态。

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

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

在你的 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();
}

推荐阅读