Joh*_*nha 8 java logic android android-layout
我有一个'添加'按钮和一个带有6个插槽的GridLayout,当我点击'添加'按钮时,view1被添加到gridlayout中,我再次点击'添加'按钮,添加了view2,依此类推.
if (!theLayout1.isShown()) {
Grid.addView(theLayout1);
} else if (!theLayout2.isShown()) {
Grid.addView(theLayout2);
} else if (!theLayout3.isShown() ) {
Grid.addView(theLayout3);
} ..... // this goes on
Run Code Online (Sandbox Code Playgroud)
添加视图后,检查其文本是否已添加到sharedPrefs中,以便在重新创建活动时自动添加它们
if (prefs.getString("text4", null) != null) {
Grid.addView(theLayout4);
}
if (prefs.getString("text5", null) != null) {
Grid.addView(theLayout5);
}
// each view has one EditText
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我删除view1然后再添加它,它将被放置在我想要的最后一个插槽中,但是当我重新创建活动时它将返回到第一位,因为代码被读取在其中订购它将按初始顺序添加视图.
我希望在完成活动之前按顺序重新创建活动时添加视图,这可能有一个简单的逻辑解决方案,或者我只是非常错误地处理问题,无论如何,需要帮助!
问题(至少从我从你的问题中了解到的)是你没有在首选项中保存某种用于视图在其父视图中的位置的指示器。现在,首次添加与删除视图后再次添加视图之间,或者在插槽 1 与插槽 5(例如)添加视图之间没有区别。处理此问题的一种方法是在每个插槽的首选项中都有一个条目,然后在这些插槽首选项中保存视图指示器:
例如:
// the base of the slot keys, there will be 6 of them from 1 to 6 inclusive
private static final String KEY_SLOT = "key_slot";
// when adding the view for slot 2 you'll save in preferences text2 it's indicator
prefEditor.putString(KEY_SLOT + position, text2); // position will be 2, the indicator of the slot in your layout
// when you delete the view from a slot, nullify it's slot preferences
// for example deleting the slot 3(child 3 in the layout)
prefEditor.putString(KEY_SLOT + position, null); position will be 3
Run Code Online (Sandbox Code Playgroud)
当您重新创建活动时,请查看所有 SLOT 首选项并查看它们持有哪些值。如果您的布局允许有孔(例如没有插槽 2 的视图,但有插槽 1 和 3 的视图),它们可能为 null,或者它们可以保存您的 text* 变量之一,指示应将哪个视图放置在该插槽中:
// in the activity:
// iterate over all the SLOT preferences
for (int i = 1; i <= 6; i++) {
String text = prefs.getString(KEY_SLOT + i, null);
// if text is null there is no view stored for this slot
// keep in mind that you need to add some sort of empty widget to act as a child
// or modify the LayoutParams of the other children to take in consideration the empty space
// OR
// if text is one of your values, like text1, text2 etc
// then you know that at slot i you need to place the view corresponding to the text value
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
256 次 |
最近记录: |