`
007007jing
  • 浏览: 42321 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

android2.3 api demo 学习系列(8)--App/Activity/Preference State

阅读更多

android保存数据有很多种方式,其中最简单的就是使用SharedPreferences。Shared Preferences存储的是key/value键值对。支持的数据类型为:boolean、long、float、int、string、stringset。SharedPreferences在保存UI的state上最为常用方便。(application之间不能使用SharedPreferences,仅限在同一个application内activity之间共享一些数据)

 

1、创建布局

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:padding="4dip"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip" 
        android:text="@string/app_activity_persistent_state_msg"/>

    <TextView
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="@string/app_activity_persistent_state_save"/>

    <EditText android:id="@+id/app_activity_persistent_state_saved_edit"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/green"
        android:text="@string/app_activity_persistent_state_save"
        android:freezesText="true">
        <requestFocus />
    </EditText>

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingTop="8dip"
        android:paddingBottom="4dip"
        android:text="@string/app_activity_persistent_state_cancel"/>

    <EditText 
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/red"
        android:text="@string/app_activity_persistent_state_cancel">
    </EditText>

</LinearLayout>

2、在activity的onPause方法内保存数据

@Override
protected void onPause() {
	super.onPause();
	SharedPreferences.Editor editor = getPreferences(this.MODE_PRIVATE).edit();
	editor.putString("text", mEditText.getText().toString());
        editor.putInt("selection-start", mEditText.getSelectionStart());
        editor.putInt("selection-end", mEditText.getSelectionEnd());
        editor.commit();
}

  3、在activity的onResume方法内还原数据

 

@Override
protected void onResume() {
	super.onResume();
	SharedPreferences prefs = getPreferences(0); 
        String restoredText = prefs.getString("text", null);
        if (restoredText != null) {
            mEditText.setText(restoredText, TextView.BufferType.EDITABLE);

            int selectionStart = prefs.getInt("selection-start", -1);
            int selectionEnd = prefs.getInt("selection-end", -1);
            if (selectionStart != -1 && selectionEnd != -1) {
            	mEditText.setSelection(selectionStart, selectionEnd);
            }
        }
}

 效果图:


 

-----------------------------------------------------------------------------------------------------------------------

接下来我们来看看sdk中关于SharePreferences的相关介绍

SharedPreferences 类提供了基本的保存key-value对来原始数据. 你可以使用SharedPreferences保存此类数据: booleans, floats, ints, longs, and strings. 数据将会被保存到用户的session中(即使应用程序被终止)。

 

在应用程序中如果想使用 SharedPreferences 可以使用下面的两个方法:

使用SharePreferences写入数据的步骤:
  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()
同样对应的存在get方法来读取数据
示例:
public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}
 
  • 大小: 45.4 KB
分享到:
评论

相关推荐

    Android代码-Material Design风格Preference UI

    implementation 'moe.shizuku.preference:preference-dialog-android:' //implementation 'moe.shizuku.preference:preference-dialog-appcompat:' // if you want to use appcompat version dialog //...

    Android-Support-Preference-V7-Fix-master.zip

    标题中的"Android-Support-Preference-V7-Fix-master"表明这是一个针对Android支持库中Preference-V7组件的修复项目。在Android开发中,Support Library(现在称为AndroidX库)是谷歌提供的一系列兼容库,用于帮助...

    Android应用源码之Preference_Demo-IT计算机-毕业设计.zip

    本项目"Android应用源码之Preference_Demo"是一个毕业设计示例,它深入展示了如何在Android应用程序中创建和管理用户偏好设置。通过分析这个源码,我们可以学到以下几个关键知识点: 1. **Preference组件**: - `...

    android-support-v7-preference.jar

    android-support-v7-preference.jar

    android-support-v4-v7-v13-v14-v17(官方最新完整版)

    android-support-v4-v7-v13-v14-v17(官方最新完整版),官方最新版的,压缩包内包含android-support-v4、android-support-v7-appcompat,android-support-v7-cardview,android-support-v7-gridlayout,android-support-...

    安卓Android源码——Preference_Demo.rar

    10. **总结**:Preference_Demo示例项目旨在帮助开发者理解和掌握Android中的设置界面实现,通过这个例子,可以学习到如何创建、配置和管理设置项,以及如何处理用户输入,从而提升应用的用户体验。

    android Preference自定义样式

    Preference通常在XML布局文件中定义,并通过`&lt;preference-headers&gt;`标签在设置活动中声明。例如: ```xml &lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;PreferenceCategory ...

    android-support-v7-preference

    android-support-v7-preference,我是编译Ijkplayer的时候需要用到。这个是6.0之后的.

    Android_api_demo

    ### Android API Demo 知识点概述 #### 一、概览 本文档旨在全面解析 Android API Demo 中的各种案例,通过具体实例深入理解 Android 开发中的关键技术和应用实践。该文档覆盖了从简单的用户界面设计到复杂的后台...

    annotations.zip

    Android Build 时报错: java.io.IOException: Could not parse XML from android/accounts/annotati...Android构建时报错: app:lintVitalRelease[Fatal Error] :3:214: 与元素类型 “item” 相关联的 “name” ...

    android Preference的Demo

    本Demo旨在展示如何在Android应用中使用Preference来实现用户设置的保存与读取。 首先,我们需要在布局文件(通常是res/xml/preference.xml)中定义Preference视图。这个XML文件包含了各种Preference类型的节点,如...

    高级路由--介绍ccnp/ccie高级路由实验,掌握cisco高级路由知识

    4. **BGP(Border Gateway Protocol)**: "Configuring IBGP and EBGP Sessions, Local Preference and.doc"涵盖了内部BGP(IBGP)和外部BGP(EBGP)的配置,以及本地优先级的设定。BGP是互联网上广泛使用的外部网关...

    android preference framework demo

    此DEMO内含基本的android preference framework的简单介绍,包括CheckboxPreference, RingtonePreference, EditTextPreference以及ListPreference。主要探究了一下android 怎么通过使用preference从而达到对用户定制...

    Android Preference解读

    在Android开发中,Preference是用于构建用户界面的一种重要组件,特别是在设置界面的实现上。它提供了许多预定义的UI元素,如开关按钮、选择列表、输入框等,使得开发者能够快速构建具有交互性的配置界面。本篇文章...

    jacob-1.17-M2(32/64)和jacob.jar包

    使用前操作 1、把dll文件放在%JAVA_HOME%\bin下(注意系统是32位... 2、如果是在eclipse下开发,需要重新引入jdk(Preference/Java/Installed JREs) 3、开发时将jacab.jar包放在项目lib下并add到liabraries中即可。

    Android代码-Socialoid-Preference-Library

    Socialoid-Preference-Library Custom preference view for preference screens on Android. Each social icon is selectable in the normal view. If the user clicks on the title, the dialog appears which is ...

    android支持包:android-support-v4

    Android Support Library V4,简称`android-support-v4`,是Android开发者广泛使用的库,旨在提供对Android早期版本的兼容性,同时包含许多先进的特性,使得应用能够运行在从Android 2.1 (API级别7)到最新的Android...

    android Preference Demo

    《Android中的Preference Demo详解》 在Android开发中,Preference是一个重要的组件,用于创建用户界面,让用户可以方便地进行设置和偏好选择。Preference Demo是展示如何使用Preference进行UI设计的一个实例,它...

    Android中Preference的使用以及监听事件分析

    在Android开发中,Preference是构建用户界面的一种重要方式,它主要用于创建设置界面,提供开关、选择列表、输入框等常用控件。Preference类是Android框架的一部分,它简化了UI元素的创建和管理,使得开发者可以方便...

Global site tag (gtag.js) - Google Analytics