简体   繁体   English

使用以前以编程方式添加的按钮保存/加载 Android 布局

[英]Saving/loading an Android layout with previously programmatically added buttons

I have a very simple question about loading layout in main activity.我有一个关于在主要活动中加载布局的非常简单的问题。 I have a simple layout defined in activity_main.xml which is loaded in MainActivity's OnCreate() using我在 activity_main.xml 中定义了一个简单的布局,它使用 MainActivity 的 OnCreate() 加载

setContentView(R.layout.activity_main).

Then on a button click, I add another view item (button) which shows up correctly.然后单击按钮,我添加了另一个正确显示的视图项(按钮)。

But when the app is closed and opened again, I need to retain what was added last time when the app closed.但是当应用程序关闭并再次打开时,我需要保留上次关闭应用程序时添加的内容。 How do I do that?我怎么做?

I searched some questions here, but most of them talk about saving values using SharedPreferences or saving state, but it is not clear if the layout can be saved as well.我在这里搜索了一些问题,但大多数都谈到使用 SharedPreferences 或保存状态来保存值,但不清楚是否也可以保存布局。

Thanks in advance.提前致谢。

I think the best solution is saving latest state values by using SharedPreferences , because it is a good way to save any simple data for long term.我认为最好的解决方案是使用SharedPreferences保存最新的状态值,因为这是长期保存任何简单数据的好方法。

Saving state via using saveInstanceState is a short term solution and if you close your app completely, saved instance will be gone forever.通过使用saveInstanceState保存状态是一个短期解决方案,如果您完全关闭您的应用程序,保存的实例将永远消失。

Possible solution:可能的解决方案:

First, you cannot save a layout as you think, but you can get the layout's parameters and other features as variables , then you can save these by using SharedPreferences .首先,你不能像你想象的那样保存布局,但你可以将布局的parameters和其他特性作为variables ,然后你可以使用SharedPreferences保存这些。

Secondly, you should check if there is any saved layout states when you start the activity.其次,您应该在启动Activity 时检查是否有任何已保存的布局状态。 If any, you can use the pre-saved parameters for adding your layout dynamically/programmatically.如果有的话,您可以使用预先保存的参数以动态/编程方式添加您的布局。

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

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