移动活动时保留列表条目



我有一个ListView。我从2个editText填充此列表当我移动活动并返回到它时,条目将再次消失。我有点理解为什么会这样,但不知道如何纠正。

    ListView lv2 = (ListView) findViewById(R.id.listView2);
    final SimpleAdapter simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[]{"planet"}, new int[]{android.R.id.text1});
    planetsList.add(createPlanet("planet", "testme"));
    lv2.setAdapter(simpleAdpt);

    button21.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            iinitList();
            simpleAdpt.notifyDataSetChanged();
            editText5.setText("");
            editText6.setText("");
        }
    });
}


    private void iinitList() {
    String st,str;
    Double db;
    if (editText5.getText().toString()!= "" && editText6.getText().toString()!="") {
        st = editText5.getText().toString();
        str = editText6.getText().toString();
        db = Double.parseDouble(str);
            planetsList.add(createPlanet("planet", ""+st+
                    ": n" +db+""));
    }
}
HashMap<String, String> createPlanet(String key, String name) {
    HashMap<String, String> planet = new HashMap<String, String>();
    planet.put(key, name);
    return planet;
}

正如你所看到的,我已经手动向列表中添加了一个名为test的值,当我移动活动时,它会保留在列表中,如果在我移动活动的时候,editText条目也会保留在那里,我会很高兴。

当您导航到新的活动或轮换时,活动可能会被销毁。这将清除仅由活动引用的任何内容,如EditText。然而,Android提供了一个很好的实用程序,可以将您想要保留的东西保存在名为的方法中,您可以在活动中覆盖该方法:

@Override
protected void onSaveInstanceState(Bundle state) {
    // Put your values in the state bundle here
}
@Override
protected void onCreate(Bundle savedState) {
    // Load your UI elements as usual
    if (savedState != null) {
        // Load your state from the bundle
    }
}

相同的捆绑包将在onCreate中返回给您,在那里您可以创建UI,以便从中重新加载状态

这是对活动如何运作的一个非常好的描述:http://developer.android.com/reference/android/app/Activity.html

最新更新