保存动态添加的视图

时间:2018-10-17 09:04:13

标签: android android-linearlayout

我想将动态添加的视图保存在布局中。因此,当我回到自己的活动时,我想找到我添加的视图。这是我添加视图的代码

代码:

public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
    if (check == true) {
        SanksionLabel = (ViolationDTO) SpinnerSanksioni.getSelectedItem();
        Log.d("Yes", SanksionLabel.toString());
        final LinearLayout rootLayout = rootView.findViewById(R.id.layout_shkelja);
        if (!sanksionetArray.contains(SanksionLabel)) {
            LinearLayout linearLayout1 = new LinearLayout(getActivity().getBaseContext());
            linearLayout1.setOrientation(LinearLayout.HORIZONTAL);
            TextView sanksionivalue = new TextView(getActivity().getBaseContext());
            sanksionetArray.add(SanksionLabel);
            sanksionivalue.setText(counttextview + ". " + SanksionLabel);
            sanksionivalue.setTag(counttextview + "txtview");
            sanksionivalue.setTextColor(R.color.Black);
            sanksionivalue.setTextSize(20);
            sanksionivalue.setTypeface(Typeface.DEFAULT_BOLD);
            LinearLayout.LayoutParams paramssanksioni = new LinearLayout.LayoutParams(600, LinearLayout.LayoutParams.WRAP_CONTENT);
            paramssanksioni.setMargins(0, 8, 0, 0);
            sanksionivalue.setLayoutParams(paramssanksioni);
            linearLayout1.addView(sanksionivalue, 0);
            btnfshishkeljen = new ImageView(getActivity().getBaseContext());
            btnfshishkeljen.setBackgroundResource(R.drawable.ic_delete_textview_24dp);
            btnfshishkeljen.setTag("tag" + count);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(60, 60);
            btnfshishkeljen.setLayoutParams(params);
            linearLayout1.addView(btnfshishkeljen, 1);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(40, 20, 30, 0);
            linearLayout1.setBackground(getResources().getDrawable(R.drawable.textview_underline));
            linearLayout1.setTag("tag" + count + "linear");
            rootLayout.addView(linearLayout1, 2, layoutParams);
            count++;
            counttextview++;
        } 
    }
}

1 个答案:

答案 0 :(得分:0)

当“活动”停止时(例如,当您切换到另一个应用程序时),当您返回到活动时,该活动将重新启动。在这种情况下,您将丢失例如在运行时添加的布局。

您可以做的是重写功能onSaveInstanceState(Bundle outState),在此功能之前,您可以保存活动的当前状态,然后再将其停止。返回活动时,将调用函数onCreate(Bundle savedInstanceState),您可以在其中将视图还原到停止之前的状态。

有关详细信息,请参阅文章https://developer.android.com/guide/components/activities/activity-lifecycle#java