【发布时间】:2015-04-27 03:35:32
【问题描述】:
我有一个 Android 应用程序,它允许用户将自己的按钮动态添加到布局中。我需要这样做,以便一旦应用程序关闭并重新打开,这个动态添加的按钮就会返回到布局。而不是加载默认布局。
目前我是通过App的ActionBar动态添加按钮:
if (id == R.id.add_button)
{
String string = "Adding Button in Progress";
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show( );
Button myButton = new Button(this);
myButton.setText("Button");
RelativeLayout layout = (RelativeLayout)findViewById(R.id.Layout1);
layout.addView(myButton);
//myButton.setVisibility(View.VISIBLE);
return true;
}
这可以很好地创建按钮,但是当应用程序关闭并重新打开时,它会启动默认布局。
我对让应用保存并重新加载更新后的布局进行了一些研究。看来我需要使用onSaveInstanceState。以下是我迄今为止尝试保存布局的内容:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the app state here:
savedInstanceState.putAll(savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
这就是我在尝试“重新加载/恢复”所述布局方面所拥有的。请注意,我没有使用 onRestoreInstanceState,而是通过 onCreate 方法进行操作:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
//savedInstanceState.get(savedInstanceState);
}
else
{
//initialize members with default values for a new instance
setContentView(R.layout.activity_main);
}
}
我不确定我的保存/加载是否正确,但我将不胜感激有关如何完成此任务的任何建议。
感谢您的宝贵时间!
附:我仍然是一个相当新的成员,所以我无法对现有线程发表评论/提问。
我知道有很多关于尝试加载/保存布局的信息,但在我的情况下,我需要它来保存按钮,而不是用户文本字符串。换句话说,它不是我需要保存的固定值。如果用户添加了 n 个按钮,当应用程序退出并重新启动时,它应该具有相同的 3 个按钮。
【问题讨论】:
-
结合 ViewStub 和 SharedPreferences 将解决您的问题。
-
@VVB:感谢您的回复。我之前尝试过查看 SharedPreferences 但被拒绝了,因为我不确定如何将活动的状态(即最近添加的按钮)表示为 SharedPreferences 似乎需要的键值对。
标签: android android-layout android-activity savestate