Android - 如何保存以编程方式创建的视图并在应用程序重新启动时恢复它

时间:2013-05-22 16:32:51

标签: android android-layout android-view

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

@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);

        }
    }
}

我可以在不使用数据库的情况下保存吗?

2 个答案:

答案 0 :(得分:1)

您可以通过4种方式在Android设备上保存数据:SharedPreferences,DB,File或服务器。有关详细信息,请参阅here

答案 1 :(得分:1)

保存/恢复的密钥是唯一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的简单方法是静态。

文件ids.xml(在res / values中)

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