如何在销毁活动时保存动态表的状态?

时间:2015-02-01 22:52:19

标签: android sharedpreferences

我有一个TableLayout,我根据用户输入动态添加行。我希望这个表在活动被销毁时保持其值(即旋转,后退按钮)。

我知道我可以将此表的值作为单独的值输入到SharedPreferences映射中,但这将涉及在活动恢复时手动重建表。

除了对所有单个元素使用SharedPreferences之外,是否有更优雅的解决方案来保存表格?

2 个答案:

答案 0 :(得分:0)

我指的是保存数据类中的项目并序列化该数据类,例如(TableLalyoutstorage.java其中包含项目的数据),因此您需要更改布局接收数据的方式,它应该首先保存到数据类对象,然后再添加它..

但是我还没有尝试过,但你可以序列化视图)你也试过这个

所以如果你有一个ViewGroup TableLayout恰好是一个,你就可以做到这一点

ArrayList<View> myViews = null; // this is declared globally, view container
// in initialising lifecycles of android eg oncreate
TableLayout tl = View.findViewById(R.id.tl)// thats my initialising of table layout.. 
//we already has or have Views added to it
// all this in my oncreate
FileInputStream fiss;
try {
    fiss = Activity.openFileInput("dataName"); // dataName is the name you want to save it on disk
    ObjectInputStream oi = new ObjectInputStream(fiss);
    myViews = ((ArrayList<View>) oi.readObject()); // it will read from disk
    oi.close();
    fiss.close();
}catch(Exception e){}
//after that
if(myViews !=null && !myViews.isEmpty()){
     for(int i = 0; i < myViews.size(); i++){
           tl.addView(myViews.get(i)); // add params and stuff
     }
 }
 // with that your `ViewGroup` now has it views

然后可能在你的结束生命中,你保存你的观点

myViews.clear();
for(int i =0; i < tl.getChildCount(); i++){
      myViews.add(tl.getChildAt(i));
   }
// we noww save to disk
try {
   FileOutputStream foss = Activity.openFileOutput("dataName", Context.MODE_PRIVATE);
   ObjectOutputStream off = new ObjectOutputStream(foss);
   off.writeObject(myViews);
   off.flush();
   off.close();
   foss.close();}catch (Exception e) {}

不要忘记检查我的大括号,或缩进,我是一个非常糟糕的文本代码编写者..

希望它可以帮助你..

答案 1 :(得分:0)

您可以覆盖onSaveInstanceState(Bundle)以保留恢复活动时需要使用的数据,并onCreate(Bundle)使用以前保留的数据(如果有)重建您的UI。这假设您的数据要么实现Parcelable,要么是可以添加到Bundle

的类型之一

我以前从未尝试过使用TableLayout这种方法,可能即使数据恢复你的视图状态也会改变(比如滚动位置),但至少你会看到包含完整数据的表格。或者,您可以试用GridViewRecyclerView,它使用Adapter来绑定数据,并且可以更好地支持视图状态恢复。

相关问题