Android - Preferences

Android - Preferences 首页 / Android入门教程 / Android - Preferences

Android共享首选项用于存储和检索原始信息。在android中,string,integer,long,number等被视为原始数据类型。

Android共享首选项用于存储键和值对中的数据,以便无涯教程可以根据键查询值。

首选项示例

让无涯教程看一下Android共享首选项的一个简单示例。

android preference directory output 1


从面板上拖动一个textview和两个按钮。

File: activity_main.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<relativelayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="example.learnfk.com.preferences.MainActivity">
    <textview android:id="@+id/txtPrefs" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centervertical="true" android:text="Data:"></textview>
    <button android:id="@+id/storeinformation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/showinformation" android:layout_centerhorizontal="true" android:layout_margintop="18dp" android:text="Store Information"></button>
    <button android:id="@+id/showinformation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="17dp" android:text="Show Information"></button>
</relativelayout>

它是在res/values目录中创建的。

File: array.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<resources>
    <string-array name="listOptions">
        <item>English</item>
        <item>Hindi</item>
        <item>Other</item>
    </string-array>
    <string-array name="listValues">
        <item>English Language</item>
        <item>Hindi Language</item>
        <item>Other Language</item>
    </string-array>
</resources>

它是在Res/XML目录中创建的。

File: prefs.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<preferencescreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <preferencecategory android:summary="Username and password information" android:title="Login information">
        <edittextpreference android:key="username" android:summary="Please enter your login username" android:title="Username"></edittextpreference>
        <edittextpreference android:key="password" android:summary="Enter your password" android:title="Password"></edittextpreference>
    </preferencecategory>
    <preferencecategory android:summary="Username and password information" android:title="Settings">
        <checkboxpreference android:key="checkBox" android:summary="On/Off" android:title="Keep me logged in"></checkboxpreference>
        <listpreference android:entries="@array/listOptions" android:entryvalues="@array/listValues" android:key="listpref" android:summary="List preference example" android:title="List preference"></listpreference>
    </preferencecategory>
</preferencescreen>
File: MainActivity.java
package example.learnfk.com.preferences;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button storeinformation = (Button) findViewById(R.id.storeinformation);
        Button showinformation = (Button) findViewById(R.id.showinformation);
        textView = (TextView) findViewById(R.id.txtPrefs);

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.storeinformation:
                        Intent intent = new Intent(MainActivity.this,PrefsActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.showinformation:
                        displaySharedPreferences();
                        break;
                    default:
                        break;
                }
            }
        };
        storeinformation.setOnClickListener(listener);
        showinformation.setOnClickListener(listener);
    }


    private void displaySharedPreferences() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        String username = prefs.getString("username", "Default NickName");
        String passw = prefs.getString("password", "Default Password");
        boolean checkBox = prefs.getBoolean("checkBox", false);
        String listPrefs = prefs.getString("listpref", "Default list prefs");


        StringBuilder builder = new StringBuilder();
        builder.append("Username: " + username + "\n");
        builder.append("Password: " + passw + "\n");
        builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
        builder.append("List preference: " + listPrefs);
        textView.setText(builder.toString());

    }

}
File: PrefsActivity.java
package example.learnfk.com.preferences;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class PrefsActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
    }
}
File: AndroidManifest.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android" package="example.learnfk.com.preferences">
    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundicon="@mipmap/ic_launcher_round" android:supportsrtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>
        </activity>
        <activity android:name=".PrefsActivity" android:theme="@android:style/Theme.Black.NoTitleBar"></activity>
    </application>
</manifest>

输出:

android preference example output 1android preference example output 2android preference example output 3android preference example output 4

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

从0开始学游戏开发 -〔蔡能〕

Linux实战技能100讲 -〔尹会生〕

分布式协议与算法实战 -〔韩健〕

etcd实战课 -〔唐聪〕

Spring编程常见错误50例 -〔傅健〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

中间件核心技术与实战 -〔丁威〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)