簡體   English   中英

如何在按下按鈕時動態更改圖片並保存該圖片的狀態

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

大家早上好。

我有一個問題,我需要在按下Button時更改imageView的圖像,並在再次按下Button時更改為先前的圖像。 我什至設法通過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;                   
        }
    }
});

}

嘗試以這種方式進行。 您需要自己保存狀態。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM