0

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

4

3 回答 3

1

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

于 2012-05-10T18:33:59.243 回答
0

查看文档以覆盖默认旋转行为:http: //developer.android.com/guide/topics/resources/runtime-changes.html

于 2012-05-10T02:44:54.440 回答
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

>

于 2012-05-10T04:45:10.613 回答