欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Android首選項(xiàng)框架的使用實(shí)例

 更新時(shí)間:2016年11月16日 16:43:47   作者:liuhe688  
首選項(xiàng)這個(gè)名詞對(duì)于熟悉Android的朋友們一定不會(huì)感到陌生,它經(jīng)常用來設(shè)置軟件的運(yùn)行參數(shù)。本篇文章主要介紹詳解Android首選項(xiàng)框架的使用實(shí)例,有興趣的可以了解一下。

首選項(xiàng)這個(gè)名詞對(duì)于熟悉Android的朋友們一定不會(huì)感到陌生,它經(jīng)常用來設(shè)置軟件的運(yùn)行參數(shù)。

Android提供了一種健壯并且靈活的框架來處理首選項(xiàng)。它提供了簡(jiǎn)單的API來隱藏首選項(xiàng)的讀取和持久化,并且提供了一個(gè)優(yōu)雅的首選項(xiàng)界面。

首先,我們來看下面這款軟件的首選項(xiàng)界面:

這款軟件使用了好幾種類型的首選項(xiàng),每一種首選項(xiàng)都有其獨(dú)特的用法,下面我們來了解一下幾種常見的首選項(xiàng):

  • CheckBoxPreference:用來打開或關(guān)閉某個(gè)功能
  • ListPreference:用來從多個(gè)選項(xiàng)中選擇一個(gè)值;
  • EditTextPreference:用來配置一段文字信息;
  • Preference:用來執(zhí)行相關(guān)的自定義操作(上圖中的清除緩存、歷史記錄、表單、cookie都屬于此項(xiàng));
  • RingtonePreference:專門用來為用戶設(shè)置鈴聲。

當(dāng)我們使用首選項(xiàng)框架時(shí),用戶每更改一項(xiàng)的值后,系統(tǒng)就會(huì)立即在/data/data/[PACKAGE_NAME]/shared_prefs下生成一個(gè)[PACKAGE_NAME]_preferences.xml的文件,文件會(huì)記錄最新的配置信息。

那么如何使用首選想框架呢?我們需要以下幾步操作:

1.建立一個(gè)首選項(xiàng)的xml配置文件,放在項(xiàng)目的/res/xml目錄下面;

2.新建一個(gè)Activity,繼承android.preference.PreferenceActivity,然后在onCreate方法中加載我們的首選項(xiàng)配置文件。

下面,我就為大家演示一下首選項(xiàng)框架的配置和使用:

我們新建一個(gè)prefs項(xiàng)目,項(xiàng)目結(jié)構(gòu)如下:

我們要實(shí)現(xiàn)的功能跟上面那款軟件的很相似,下面我來說明一下這個(gè)項(xiàng)目的整體流程:

1.主界面。顯示用戶昵稱,有三個(gè)參數(shù),昵稱文字、字體大小和背景顏色。首次進(jìn)入時(shí),使用默認(rèn)值。

2.按下menu鍵中的settings項(xiàng),跳轉(zhuǎn)到首選項(xiàng)頁(yè)面,進(jìn)行參數(shù)選擇。

3.按下返回鍵,返回主界面,設(shè)定后的參數(shù)生效。

首先,讓我們來看一下主界面的配置文件,非常簡(jiǎn)單,就一個(gè)TextView:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent"> 
  <TextView 
    android:id="@+id/textView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_horizontal" 
    android:textColor="#FF0000"/> 
</LinearLayout> 

然后,我們需要在主界面里根據(jù)配置參數(shù)設(shè)置TextView的外觀以及背景,MainActivity.java代碼如下:

package com.scott.prefs; 
 
import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
  private static final int SETTINGS_ID = 0; 
  private static final int EXIT_ID = 1; 
 
  private TextView textView; 
 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    textView = (TextView) findViewById(R.id.textView); 
    showSettings(); 
  } 
 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    super.onCreateOptionsMenu(menu); 
    menu.add(0, SETTINGS_ID, 0, "Settings"); 
    menu.add(0, EXIT_ID, 0, "Quit"); 
    return true; 
  } 
 
  @Override 
  public boolean onOptionsItemSelected(MenuItem item) { 
    if (item.getItemId() == SETTINGS_ID) { 
      Intent intent = new Intent(MainActivity.this, PrefsActivity.class); 
      //如果requestCode >= 0 則返回結(jié)果時(shí)會(huì)回調(diào) onActivityResult()方法 
      startActivityForResult(intent, 1); 
    } else { 
      finish(); 
    } 
    return true; 
  } 
 
  @Override 
  protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    showSettings(); 
  } 
 
  private void showSettings() { 
    String prefsName = getPackageName() + "_preferences";  //[PACKAGE_NAME]_preferences 
    SharedPreferences prefs = getSharedPreferences(prefsName, Context.MODE_PRIVATE); 
 
    String nickName = prefs.getString("nickName", "機(jī)器人"); 
    textView.setText("歡迎您:" + nickName); 
 
    boolean nightMode = prefs.getBoolean("nightMode", false); 
    textView.setBackgroundColor(nightMode ? Color.BLACK : Color.WHITE); 
 
    String textSize = prefs.getString("textSize", "0"); 
    if (textSize.equals("0")) { 
      textView.setTextSize(18f); 
    } else if (textSize.equals("1")) { 
      textView.setTextSize(22f); 
    } else if (textSize.equals("2")) { 
      textView.setTextSize(36f); 
    } 
  } 
} 

可以看到,進(jìn)入主界面之后會(huì)根據(jù)[PACKAGE_NAME]_preferences獲取首選項(xiàng)配置信息,如果是首次進(jìn)入,則使用默認(rèn)值,下面就是我們首次進(jìn)入主界面時(shí)的畫面:

可以看到,我們初次進(jìn)入的界面時(shí)昵稱為“機(jī)器人”,字的背景為白色,字的大小為18號(hào)。

然后按下Settings之后,我們就可以進(jìn)行首選項(xiàng)的配置了,讓我們先來看一下settings.xml的配置:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" 
  android:key="settings" 
  android:title="軟件設(shè)置"> 
  <PreferenceCategory 
    android:key="basic" 
    android:title="基本設(shè)置"> 
    <EditTextPreference 
      android:key="nickName" 
      android:title="昵稱" 
      android:defaultValue="機(jī)器人"/> 
    <CheckBoxPreference 
      android:key="nightMode" 
      android:title="夜間模式" 
      android:summaryOn="已啟用" 
      android:summaryOff="未啟用"/> 
    <ListPreference 
      android:key="textSize" 
      android:title="文字大小" 
      android:dialogTitle="文字大小" 
      android:entries="@array/textSize_entry" 
      android:entryValues="@array/textSize_entry_value" 
      android:defaultValue="0"/> 
  </PreferenceCategory> 
  <PreferenceCategory 
    android:key="clean" 
    android:title="清除記錄"> 
    <Preference  
      android:key="cleanHistory" 
      android:title="清除歷史記錄" />   
  </PreferenceCategory> 
</PreferenceScreen> 

其中,最外層是PreferenceScreen標(biāo)簽,代表一系列首選項(xiàng)的集合;然后,我們注意到PreferenceCategory這一項(xiàng),此標(biāo)簽代表一個(gè)類別,可以包含多個(gè)首選項(xiàng);最后就是我們用于配置參數(shù)的首選項(xiàng)了。需要了解的是,PreferenceScreen也可以嵌套使用,也就是說上面的PreferenceCategory可以替換成PreferenceScreen。

此外,我們還需要了解一下文件中出現(xiàn)的幾個(gè)常用標(biāo)簽屬性:

  • android:key  選項(xiàng)的名稱或鍵
  • android:title  選項(xiàng)的標(biāo)題
  • android:summary  選項(xiàng)的簡(jiǎn)短摘要
  • android:entries  列表項(xiàng)的文本
  • android:entryValues  列表中每一項(xiàng)的值
  • android:dialogTitle  對(duì)話框標(biāo)題
  • android:defalutValue  列表中選項(xiàng)的默認(rèn)值
  • 對(duì)于CheckBoxPreference還有兩個(gè)特殊的屬性
  • android:summaryOn  選項(xiàng)被選中時(shí)顯示的摘要
  • android:summaryOff  選項(xiàng)未選中時(shí)顯示的摘要

我們還可以看到,在ListPreference中,entries來自于textSize_entry,而entryValues來自于textSize_entry_value,這兩項(xiàng)都在/res/values目錄下的text_size.xml配置:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
  <string-array name="textSize_entry"> 
    <item>小</item> 
    <item>中</item> 
    <item>大</item> 
  </string-array> 
  <string-array name="textSize_entry_value"> 
    <item>0</item> 
    <item>1</item> 
    <item>2</item> 
  </string-array> 
</resources> 

配置完成之后,我們就剩下最后一步了,創(chuàng)建Activity,繼承PreferenceActivity,加載首選項(xiàng)資源文件,處理相應(yīng)的選項(xiàng)事件。

PrefsActivity.Java代碼如下:

package com.scott.prefs; 
 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.preference.EditTextPreference; 
import android.preference.ListPreference; 
import android.preference.Preference; 
import android.preference.PreferenceActivity; 
import android.preference.PreferenceScreen; 
import android.widget.Toast; 
 
public class PrefsActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener { 
 
  private EditTextPreference nickName; 
  private ListPreference textSize; 
  private Preference cleanHistory; 
 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    addPreferencesFromResource(R.xml.setttings); 
    nickName = (EditTextPreference) findPreference("nickName"); 
    textSize = (ListPreference) findPreference("textSize"); 
    cleanHistory = findPreference("cleanHistory"); 
 
    //為nickName和textSize注冊(cè)Preference.OnPreferenceChangeListener監(jiān)聽事件 
    //當(dāng)值更改時(shí)我們可以立即更新summary 
    nickName.setOnPreferenceChangeListener(this); 
    textSize.setOnPreferenceChangeListener(this); 
 
    initSummary(); 
  } 
 
  //初始化summary 
  private void initSummary() { 
    nickName.setSummary(nickName.getText()); 
 
    setTextSizeSummary(textSize.getValue()); 
  } 
 
  private void setTextSizeSummary(String textSizeValue) { 
    if (textSizeValue.equals("0")) { 
      textSize.setSummary("小"); 
    } else if (textSizeValue.equals("1")) { 
      textSize.setSummary("中"); 
    } else if (textSizeValue.equals("2")) { 
      textSize.setSummary("大"); 
    } 
  } 
 
  /** 
   * 重寫PreferenceActivity的onPreferenceTreeClick方法 
   * 在首選項(xiàng)被點(diǎn)擊時(shí) 做出相應(yīng)處理操作 
   */ 
  @Override 
  public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { 
    if (preference == cleanHistory) { 
      new AlertDialog.Builder(this) 
          .setTitle("清除歷史記錄") 
          .setMessage("是否真的要清除歷史記錄?") 
          .setPositiveButton("是", new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
              //cleaning history... 
              Toast.makeText(PrefsActivity.this, "清除成功", Toast.LENGTH_SHORT).show(); 
            } 
          }).setNegativeButton("否", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
          dialog.dismiss(); 
        } 
      }).create().show(); 
    } 
    return true; 
  } 
 
  /** 
   * 重寫Preference.OnPreferenceChangeListener的onPreferenceChange方法 
   * 當(dāng)首選項(xiàng)的值更改時(shí) 做出相應(yīng)處理操作 
   */ 
  @Override 
  public boolean onPreferenceChange(Preference preference, Object newValue) { 
    if (preference == nickName) { 
      nickName.setSummary(newValue.toString()); 
    } else if (preference == textSize) { 
      setTextSizeSummary(newValue.toString()); 
    } 
    return true; 
  } 
} 

最后,別忘了在AndroidManifest.xml中加入此Activity配置信息:

<activity android:name=".PrefsActivity"/> 

當(dāng)然我們也可以配置一下<intent-filter></intent-filter>屬性。

經(jīng)過以上幾步,我們的首選項(xiàng)配置就完成了,首次進(jìn)入的界面如下:
然后我們分別更改昵稱、夜間模式、文字大小,如下:
可以看到,當(dāng)我們更改了選項(xiàng)的值之后,摘要部分已經(jīng)設(shè)置為最新值了,此時(shí)在我們應(yīng)用下的shared_prefs目錄中生成一個(gè)com.scott.prefs_preferences.xml文件,如圖:

內(nèi)容如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?> 
<map> 
  <boolean name="nightMode" value="true" /> 
  <string name="nickName">scott</string> 
  <string name="textSize">2</string> 
</map> 

此時(shí),我們按回退鍵,回到主界面,發(fā)現(xiàn)剛才的設(shè)置已經(jīng)生效了:

可以看到,昵稱已經(jīng)更改成“scott”,字的背景已更改為黑色,字的大小已更改為36號(hào)。

如果我們?cè)谑走x項(xiàng)界面按下清除歷史記錄一項(xiàng),將會(huì)出現(xiàn)一下界面:

原文鏈接:http://blog.csdn.net/liuhe688/article/details/6448423

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論