当app被杀死时,在linearLayout中安全动态创建视图

时间:2017-07-20 11:53:55

标签: java android xml

以下是问题及其原因:

应用 我的小应用程序允许用户将一些文本输入到editText中,并且onClick可以将其显示为带有textle的checkBox,位于下面的linearLayout中。

初始状况: 我使用onSaveInstanceState()和onRestoreInstanceState()方法保存变量,只有方向更改时它才能正常工作,但是如果应用程序退出并全新打开...

问题: 如何保护checkBoxes / LinealLayout,以便每次用户关闭并重新打开应用程序时都不会重置列表?

Java代码:

public class MainActivity extends AppCompatActivity {
    int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
    int i;
    public CheckBox[] checkBox;
    public CheckBox[] checker;
    public String speicher;
    public String bringer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layout = (LinearLayout) findViewById(R.id.layout);
        button = (ImageButton) findViewById(R.id.button);
        button.setId(R.id.id);
        editText = (EditText) findViewById(R.id.editText);
        clear = (ImageButton) findViewById(R.id.delete);
        parent = (RelativeLayout) findViewById(R.id.parent);
        scroller = (ScrollView) findViewById(R.id.scroller);

    }


    public void deleteAllBoxes() {

        Toast.makeText(getBaseContext(), "List cleared", Toast.LENGTH_SHORT).show();

        layout.removeAllViews();
        editText.setText("");
        checkBox = null;
        checker = null;
        content.clear();


        brücke.clear();
        speicher = null;
        bringer = null;
        i = 0;
    }
}

该应用:

image

1 个答案:

答案 0 :(得分:1)

将其保存在Android的一个持久存储选项中:在您的情况下,SharedPreferences可能会很好地工作。

https://developer.android.com/guide/topics/data/data-storage.html

修改复选框后更新共享偏好设置,并使用活动onCreate中共享偏好设置中的值阅读并初始化复选框。