在屏幕旋转上保存动态创建的布局

时间:2012-05-10 01:52:08

标签: android layout dynamic

我在活动首次启动时动态创建布局,问题是当屏幕旋转时,它再次访问数据库以创建布局。如何保存布局,以便每次更改屏幕方向时都不会重新创建布局?

3 个答案:

答案 0 :(得分:1)

知道了!创建一个片段并加载在onCreate期间动态创建的视图的ArrayList。设置setRetainInstance(true);和onPause清除视图,onResume从ArrayList重新加载视图。使用setRetainInstance(true)时,不会再次调用onCreate,因此不会从DB加载。

答案 1 :(得分:0)

答案 2 :(得分:0)

你可以使用

@Override
protected void onSaveInstanceState(Bundle outState) {
    // SAVE YOUR DATA IN "outstate" BUNDLE
    super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // RESTORE YOUR DATA FROM savedInstanceState.
    super.onRestoreInstanceState(savedInstanceState);
}

保存数据包并在onRestoreInstanceState中重新恢复

这里是示例..

public class Test_stflowActivity extends Activity {
    String initial_text = null;
    boolean already_created = false;
    TextView tv = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.textView1);

        if (savedInstanceState == null) {
            initial_text = "bharat";
            loadNew();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        initial_text = "sharma";
        outState.putString("initial_text", initial_text);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        initial_text = savedInstanceState.getString("initial_text");
        loadNew();
        super.onRestoreInstanceState(savedInstanceState);
    }

    void loadNew() {
        tv.setText(initial_text);
    }
}

这里是xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="139dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout

&GT;