gpt4 book ai didi

java - 旋转屏幕时如何保存可绘制的按钮

转载 作者:搜寻专家 更新时间:2023-11-01 09:30:42 24 4
gpt4 key购买 nike

我刚读到:Saving Android Activity state using Save Instance State

这个:Android - Open resource from @drawable String

我的情况是:我有一个 Button 背景设置,当按下它时它变成绿色

button.setBackgroundResource(R.drawable.greenbutton);

如何使用 onSaveInstanceStateonRestoreInstanceState 存储此信息?

我试过:How to maintain a button style and click state after screen rotation? 并且有效 但也许还有比三嵌套 if 条件过程更好的东西?我的意思是我必须为 4+ Button 做这件事,我认为这只是一个简单的原因:)

谢谢

编辑:这是目前为止的代码

package com.example.android.testbutton;

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.change);
}

Button button;
Boolean click;

public void changeColor(View view) {
click = true;
button.setBackgroundResource(R.drawable.greenbutton);
}


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.

savedInstanceState.putBoolean("buttonClicked", click);
// etc.

super.onSaveInstanceState(savedInstanceState);
}

//onRestoreInstanceState

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);

// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.

Boolean firstAnswer = savedInstanceState.getBoolean("buttonClicked");
{
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("buttonClicked")) {
if (savedInstanceState.getBoolean("buttonClicked"))
button.setBackgroundResource(R.drawable.greenbutton);

//some codes to make the button becomes clicked.
}
}
}
}
}

最佳答案

也为您的 Activity 设置一个变量,然后保存并使用您的状态恢复它。

public class MyActivity extends Activity {

public static final String KEY_BUTTON_IS_GREEN = "isGreen";
boolean buttonIsGreen;

@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(KEY_BUTTON_IS_GREEN, buttonIsGreen);
super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
buttonIsGreen = savedInstanceState.getBoolean(KEY_BUTTON_IS_GREEN, false);
if (buttonIsGreen){
// find the button and set it green.
}
}

您需要添加将按钮设置为绿色的方法,如果按钮为绿色,还需要设置您的变量 = true。

关于java - 旋转屏幕时如何保存可绘制的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47643439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com