如何在方向更改后保存在动态创建的edittext中输入的文本

时间:2014-02-24 04:38:14

标签: android

我有2个动态创建的edittext。当输入一些文本并更改方向edittext数据丢失。 因为onSaveInstanceState调用了2次。在调试第一次我得到的价值观。但第二次值为空。

2 个答案:

答案 0 :(得分:0)

使用Shared-preferences在第一次保存数据并在更改方向后获取数据:

我希望这会对你有所帮助。使用像这样:

public static void setSharedPrefStringData(Context context, String key,
        String value) {
    SharedPreferences appInstallInfoSharedPref = context
            .getSharedPreferences(Constants.SHARED_PREF_NAME,
                    context.MODE_MULTI_PROCESS);
    Editor appInstallInfoEditor = appInstallInfoSharedPref.edit();
    appInstallInfoEditor.putString(key, value);
    appInstallInfoEditor.commit();
}

public static String getSharedPrefStringData(Context context, String key) {

    SharedPreferences userAcountPreference = context.getSharedPreferences(
            Constants.SHARED_PREF_NAME, Context.MODE_MULTI_PROCESS);

    return userAcountPreference.getString(key, "");

}

如果有任何疑虑,请告诉我。

答案 1 :(得分:0)

您可以覆盖onConfigurationChanged,请访问http://developer.android.com/reference/android/app/Activity.html

您可以按照以下方式执行此操作

 public void onConfigurationChanged(Configuration currentConfig) {
        super.onConfigurationChanged(currentConfig);

        //yours implementation with respect to edittext
    }

请尝试使用onConfigurationChanged方法并以指定方式覆盖!! 假设您有一个MainActivity主要活动 并注册表现如下

<activity android:name=".MainActivity " >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
    </intent-filter>
</activity> 

作为第一步,您可以在活动代码中添加属性android:configChanges

<activity android:name=".MainActivity "
    android:configChanges="orientation|keyboardHidden" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
    </intent-filter>
</activity>

下一步是有必要在您的活动代码中手动实现处理此布局更改的逻辑。为此,您需要覆盖该方法 MainActivity中的onConfigurationChanged()。

public void onConfigurationChanged(Configuration currentConfig) {
    super.onConfigurationChanged(currentConfig);

    //yours implementation with respect to edittext
}