现在的位置: 首页 > 综合 > 正文

android设置页面之PreferenceActivity及Preference

2014年02月24日 ⁄ 综合 ⁄ 共 7093字 ⁄ 字号 评论关闭

    离上篇博客刚好一周,希望后面会记录更多的内容,也算自己的Android笔记吧。

    本篇主要记录一般的android设置页面PreferenceActivity的使用以及与之剪不断,理还乱的Preference。
   (一)如何使用
    Android系统自带的设置应用就是利用PreferenceActivity构建的。PreferenceActivity是一个抽象类,继承于ListActivity,通过一个列表视图来展现配置页面,自己的Activity继承PreferenceActivity,在onCreate方法中由两种方式来设置列表页面,一是XML文件,使用addPreferencesFromResource(XML资源id);二是code方式,使用setPreferenceScreen(PreferenceScreen)。其实质都是由一个PreferenceScreen作为根来展开。而API中提供的现成的设置控件有:CheckBoxPreference、EditTextPreference、ListPreference、RingtonePreference以及后来的MultiSelectListPreference(API11),SwitchPreference(API14)。从XML方式显示来举个例子,相关属性都有对应的函数,所以code方式就类似了。我这里以android2.2源码中的设置为范本,在讲述如何使用系统的设置控件的同时,简单描述下自定义设置控件的使用,在2.2中设置页面还不带icon属性,需要自己定义。

    先拥有一个Settings的类继承于PreferenceActivity,加载的XML资源文件为settings.xml(其位置自己定义),代码如下:

package com.example.settings;

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

public class Settings extends PreferenceActivity { 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        addPreferencesFromResource(R.xml.settings);
    }
}

    接着定义settings.xml,根为PreferenceScreen,两个PreferenceCategory,第一个PreferenceCategory下是自定义的带icon属性项,第二个则是一个普通的preference和一个Checkbox代码如下,可以看下官网的属性定义(这里),方便理解:

<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:settings="http://schemas.android.com/apk/res/com.example.settings"
    android:key="parent"
    android:title="设置页面" >

    <PreferenceCategory android:title="自定义" >
        <com.example.settings.IconPreferenceScreen
            android:title="通用设置"
            settings:icon="@drawable/ic_settings_about" >
            <intent
                android:action="android.intent.action.MAIN"
                android:targetClass="com.example.settings.Settings"
                android:targetPackage="com.example.settings" />
        </com.example.settings.IconPreferenceScreen>
    </PreferenceCategory>
    <PreferenceCategory android:title="系统" >
        <Preference
            android:icon="@drawable/ic_settings_about"
            android:title="关于" >
        </Preference>

        <CheckBoxPreference
            android:defaultValue="true"
            android:summaryOff="没选中"
            android:summaryOn="选中了!"
            android:title="选中了吗?" >
        </CheckBoxPreference>
    </PreferenceCategory>

</PreferenceScreen>

    IconPreferenceScreen代码和对应的XML文件代码如下:

/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.settings;

import com.example.settings.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

public class IconPreferenceScreen extends Preference {

    private Drawable mIcon;

    public IconPreferenceScreen(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IconPreferenceScreen(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setLayoutResource(R.layout.preference_icon);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.IconPreferenceScreen, defStyle, 0);
        mIcon = a.getDrawable(R.styleable.IconPreferenceScreen_icon);
    }

    @Override
    public void onBindView(View view) {
        super.onBindView(view);
        ImageView imageView = (ImageView) view.findViewById(R.id.setting_icon);
        if (imageView != null && mIcon != null) {
            imageView.setImageDrawable(mIcon);
        }
    }
}

    preference_icon.xml:

<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:paddingRight="?android:attr/scrollbarSize" 
    android:orientation="horizontal">



        <ImageView
            android:id="@+id/setting_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="6dip"
            android:layout_marginRight="6dip" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="6dip"
            android:layout_marginLeft="2dip"
            android:layout_marginRight="6dip"
            android:layout_marginTop="6dip"
            android:layout_weight="1" >

            <TextView
                android:id="@android:id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="marquee"
                android:fadingEdge="horizontal"
                android:singleLine="true"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@android:id/summary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@android:id/title"
                android:layout_below="@android:id/title"
                android:maxLines="2"
                android:textAppearance="?android:attr/textAppearanceSmall" />
        </RelativeLayout>    

</LinearLayout>

    显示界面如下:

    
   需要说明的是,你得为你的IconPreferenceScreen定义自定义属性icon,在attrs.xml文件中,代码如下,这也是你settings.xml中settings属性的来源及和IconPreferenceScreen代码中mIcon对应的资源。
   

<resources>
    <declare-styleable name="IconPreferenceScreen">
        <attr name="icon" format="reference" />
    </declare-styleable>

(二)Preference的理解

    首先理解自定义的Icon是从onBindView中添加到了设置页面,它是如何做到的呢。PreferenceActivity继承ListActivity,而其中包含的ListView都会通过Adapter的getView方法来获得要显示的视图,从Preference中的源码可以发现,其getView方法会调用onBindView方法,而getView方法是会被PreferenceGroupAdapter的getView方法所调用的。
    接下来是Preference拥有保存设置值的能力,它是由PreferenceManager来统一管理的,咱们调用persistInt,persistString将值保存到SharedPreferences的xml文件中,对应的key就是在XML中定义的属性key,默认的SharedPreferences的xml文件名为应用的包名+"_preferences"。相应的我们获取该保存值也就可以通过getDefaultSharedPreferences或getSharedPreferences获得SharedPreferences后调用键值对的获取。
    最后理一下Preference思路,它类似于View。你看PreferenceScreen间接继承Preference,其成员ListAdapter为PreferenceGroupAdapter类型,负责设置内容的显示与更新;实现了 AdapterView.OnItemClickListener,当某个Item被点击时,调用该item的performClick,实现targetClass对应的Activity的启动;而具体的控件CheckBoxPreference继承Preference,根据自己的特点实现相应的方法。

    先到这吧,本来想详细的说说Preference之间的关系的,结果使用示例内容多了,以后再和ListActivity对比的理解吧。

    使用的示例可以看看:

    (1)Android软件开发之PreferenceActivity中的组件(二十八)

    (2)Android的设置界面及Preference使用

抱歉!评论已关闭.