如何保存程序创建的视图并在应用程序重启时恢复它



我从另一个活动创建了这个嵌套视图。值(要显示的文本、背景颜色等)主要由用户从其他活动输入。下面是我如何动态创建视图的代码:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                // Create a New Linear Layout
                LinearLayout ll = new LinearLayout(this);
                ll.setOrientation(LinearLayout.VERTICAL);
                LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                float scale = getResources().getDisplayMetrics().density;
                //Set Bottom Margin
                float margin = 5; //RESIZE BOTTOM MARGIN HERE!
                int margs = (int) (margin * scale + 0.5f);
                //Set padding in dp
                float padding = 5; //RESIZE PADDING HERE!
                int pads = (int) (padding * scale + 0.5f);
                llParams.setMargins(0,0,0,margs);
                //Set Parameters for Android
                ll.setLayoutParams(llParams);
                ll.setPadding(pads, pads, pads, pads);
                //Set Background Color on Layout
                String chosenColor = data.getStringExtra("sendChosenColor");
                if (chosenColor.equals("Green")){
                    ll.setBackgroundResource(R.color.HoloGreen);
                }else if (chosenColor.equals("Blue")){
                    ll.setBackgroundResource(R.color.HoloBlue);
                }else if (chosenColor.equals("Gray")){
                    ll.setBackgroundResource(R.color.HoloGray);
                }else if (chosenColor.equals("Orange")){
                    ll.setBackgroundResource(R.color.HoloOrange);
                }else {
                    ll.setBackgroundResource(R.color.HoloYellow);
                }
                //Adding Layout to Appropriate Container
                int layoutCountLeft = subjectLeft.getChildCount();
                int layoutCountRight = subjectRight.getChildCount();
                if (layoutCountLeft <= layoutCountRight){
                    subjectLeft.addView(ll);
                } else {
                    subjectRight.addView(ll);
                }
                //Create TextView for SubjectName
                TextView SubjectName = new TextView(this);
                SubjectName.setText(data.getStringExtra("sendSubjectName"));
                SubjectName.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                SubjectName.setTextSize(22);
                SubjectName.setTypeface(Typeface.DEFAULT_BOLD);
                //Create TextView for SubjectNumber
                TextView SubjectNumber = new TextView(this);
                SubjectNumber.setText(data.getStringExtra("sendSubjectNumb"));
                SubjectNumber.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                SubjectNumber.setTextSize(16);

                //Creating the divider line
                ImageView divider = new ImageView(this);
                LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
                divider.setLayoutParams(dividerParams);
                divider.setBackgroundResource(R.color.Black);
                //Add Views into the Layout
                ll.addView(SubjectNumber);
                ll.addView(SubjectName);
                ll.addView(divider);
        }
    }
}

我可以保存这个不使用数据库吗?

保存/还原的键是唯一的id。

只有设置了id的视图(无论是xml文件还是动态创建的)才能在配置更改时保持其状态,例如设备旋转。

文件CustomTextView.java

package example;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomTextView extends TextView {
    private static final String INSTANCE_STATE = "instance_state";
    private static final String VALUE          = "value";
    private int value;
    public CustomTextView(Context context) {
        this(context, null);
    }
    public CustomTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // init ...
        setId(R.id.custom_view);
        value = 123;
    }
    // methods ...
    @Override
    public Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
        bundle.putInt(VALUE, value);
            // other fields...
        return bundle;
    }
    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            value = bundle.getInt(VALUE);
                    // other fields...
            state = bundle.getParcelable(INSTANCE_STATE);
        }
        super.onRestoreInstanceState(state);
    }
}

获取唯一id的简单方法是静态的。

文件id .xml (in res/values)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="id" name="custom_view" />
</resources>

你有4种可能在Android设备上保存数据:SharedPreferences, DB, File或服务器。

最新更新