Android 完美解决自定义preference与ActivityGroup UI更新的问题

之前发过一篇有关于自定义preference 在ActivityGroup 的包容下出现UI不能更新的问题,当时还以为是Android 的一个BUG 现在想想真可笑 。其实是自己对机制的理解不够深刻,看来以后要多看看源码才行。
本篇讲述内容大致为如何自定义preference 开始到与ActivityGroup 互用下UI更新的解决方法。
首先从扩展preference开始:
类文件必须继承自Preference并实现构造函数,这里我一般实现两个构造函数分别如下(类名为:test):
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->    public test(Context context) {
  5.         this(context, null);
  6.         // TODO Auto-generated constructor stub
  7.     }
  8.     public test(Context context, AttributeSet attrs) {
  9.         super(context, attrs);
  10.         // TODO Auto-generated constructor stub
  11.     }

复制代码
这里第二个构造函数第二个参数为可以使用attrs 为我们自定义的preference 添加扩展的注册属性,比如我们如果希望为扩展的preference 添加一个数组引用,就可使用如下代码:
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->int resouceId = attrs.getAttributeResourceValue(null, "Entries", 0);
  5.         if (resouceId > 0) {
  6.             mEntries = getContext().getResources().getTextArray(resouceId);
  7.         }

复制代码
这里的mEntries 是头部声明的一个数组,我们可以在xml文件通过 Entries=数组索引得到一个数组。在这里不深入为大家示范了。
我们扩展preference 有时想让其UI更丰富更好看,这里我们可以通过引用一个layout 文件为其指定UI,可以通过实现如下两个回调函数:
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->@Override
  5.     protected View onCreateView(ViewGroup parent) {
  6.         // TODO Auto-generated method stub
  7.         return LayoutInflater.from(getContext()).inflate(
  8.                 R.layout.preference_screen, parent, false);
  9.     }

复制代码
此回调函数与onBindView 一一对应,并优先执行于onBindView ,当创建完后将得到的VIEW返回出去给onBindView处理,如下代码:
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->@Override
  5.     protected void onBindView(View view) {
  6.         // TODO Auto-generated method stub
  7.         super.onBindView(view);
  8.         canlendar = Calendar.getInstance();
  9.         layout = (RelativeLayout) view.findViewById(R.id.area);
  10.         title = (TextView) view.findViewById(R.id.title);
  11.         summary = (TextView) view.findViewById(R.id.summary);
  12.         layout.setOnClickListener(this);
  13.         title.setText(getTitle());
  14.         summary.setText(getPersistedString(canlendar.get(Calendar.YEAR) + "/"
  15.                 + (canlendar.get(Calendar.MONTH) + 1) + "/"
  16.                 + canlendar.get(Calendar.DAY_OF_MONTH)));
  17.     }

复制代码
Tip:onBindView 不是必须的,可以将onBindView 里的处理代码在onCreateView 回调函数一并完成然后返回给onBindView ,具体怎么写看自己的代码风格吧。我个人比较喜欢这种写法,比较明了。
下面我们来了解一下我扩展preference 比较常用到的几个方法:

compareTo

(

Preference

another)
与另外一个preference比较,如果相等则返回0,不相等则返回小于0的数字。

getContext

()
获取上下文

getEditor

()
得到一个SharePrefence 的Editor 对象

getIntent

()
获取Intetn

getKey

()
获取当前我们在XML为其注册的KEY

getLayoutResource

()
得到当前layout 的来源

getOnPreferenceChangeListener

()
值改变的监听事件

getPreferenceManager

()
获得一个preference管理

getSharedPreferences

()
通过获得管理获取当前的sharePreferences

getSummary

()
获得当前我们在XML为其注册的备注为summary 的值。Tip:在OnBindView 或者onCreateView 找到VIEW的时候如果存在summary 的View 对象必须为其设置summary

getTitle

()
如上,不过这里是获取标题

callChangeListener

(

Object

newValue)
如果你希望你扩展的Preference 可以支持当数值改变时候可以调用OnPreferenceChangeListener此监听方法,则必须调用此方法,查看该方法源码为:
protected
boolean callChangeListener(Object newValue) {
        
return
mOnChangeListener 
==
null
?
true
: mOnChangeListener.onPreferenceChange(
this
, newValue);
    }
    
源码简单不做过多介绍,只是实现一个接口。

getPersistedBoolean

(boolean defaultReturnValue)
获得一个保存后的布尔值,查看一下源码:
protected
boolean getPersistedBoolean(boolean defaultReturnValue) {
        
if
(
!
shouldPersist()) {
            
return
defaultReturnValue;
        }
        
        
return
mPreferenceManager.getSharedPreferences().getBoolean(mKey, defaultReturnValue);
    }
如果你有接触过sharePreference 相信一眼就能看出这里它为我们做了什么。

getPersistedFloat

(float defaultReturnValue)
如上,这里获取一个Float 的值

getPersistedInt

(int defaultReturnValue)
如上,获取一个int 的值

getPersistedLong

(long defaultReturnValue)
如上,获取一个Long 型数值

getPersistedString

(

String

defaultReturnValue)
如上,获取一个String 数值

persistBoolean

(boolean value)
将一个布尔值保存在sharepreference中,查看一下源码:
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. --> protected boolean persistBoolean(boolean value) {
  5.         if (shouldPersist()) {
  6.             if (value == getPersistedBoolean(!value)) {
  7.                 // It's already there, so the same as persisting
  8.                 return true;
  9.             }
  10.             
  11.             SharedPreferences.Editor editor = mPreferenceManager.getEditor();
  12.             editor.putBoolean(mKey, value);
  13.             tryCommit(editor);
  14.             return true;
  15.         }
  16.         return false;
  17.     }

复制代码都是sharePreference 的知识,这里不做过多介绍。其他的跟上面的都 一样,略过。
通过如上的一些设置,一个基本的扩展preference 就己经完成,下面来讲讲如果在ActivityGroup 里面让扩展的preference可以更新UI。之前 农民伯伯 探讨过,他建议我使用onContentChanged()方法,可以使UI更新 ,试了一下发现有些许问题,不过非常感谢农民伯伯。这个方法是全局刷新,则全部UI都刷新一次,但是这样不是很合理,我想了一下,那既然此方法可以更新UI那么一定可以行得通,我查看一下源码,下面把源码贴出来:
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. --> @Override
  5.     public void onContentChanged() {
  6.         super.onContentChanged();
  7.         postBindPreferences();
  8.     }
  9.     /**
  10.      * Posts a message to bind the preferences to the list view.
  11.      * <p>
  12.      * Binding late is preferred as any custom preference types created in
  13.      * {@link #onCreate(Bundle)} are able to have their views recycled.
  14.      */
  15.     private void postBindPreferences() {
  16.         if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
  17.         mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
  18.     }
  19.     
  20.     private void bindPreferences() {
  21.         final PreferenceScreen preferenceScreen = getPreferenceScreen();
  22.         if (preferenceScreen != null) {
  23.             preferenceScreen.bind(getListView());
  24.         }
  25.     }
  26. <!--
  27. Code highlighting produced by Actipro CodeHighlighter (freeware)
  28. http://www.CodeHighlighter.com/
  29. -->  
  30.     private static final int MSG_BIND_PREFERENCES = 0;
  31.     private Handler mHandler = new Handler() {
  32.         @Override
  33.         public void handleMessage(Message msg) {
  34.             switch (msg.what) {
  35.                 
  36.                 case MSG_BIND_PREFERENCES:
  37.                     bindPreferences();
  38.                     break;
  39.             }
  40.         }
  41.     };

复制代码
原来,这里它是另开一条线程来更新UI,然后当值发生变化时为其发送消息,在消息队列里面处理UI,只不过它这里继承了listActivity 更新了一整个listView ,那么我们就将它提取出来,只更新我们想要的UI则可。OK,思路出来了,下面将我扩展的一个preference 的源码提供出来:
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->package com.yaomei.preference;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import android.app.Dialog;
  9. import android.content.Context;
  10. import android.content.DialogInterface;
  11. import android.os.Handler;
  12. import android.os.Message;
  13. import android.preference.Preference;
  14. import android.preference.PreferenceGroup;
  15. import android.util.AttributeSet;
  16. import android.view.LayoutInflater;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.view.View.OnClickListener;
  20. import android.widget.AdapterView;
  21. import android.widget.ListView;
  22. import android.widget.RelativeLayout;
  23. import android.widget.SimpleAdapter;
  24. import android.widget.TextView;
  25. import android.widget.AdapterView.OnItemClickListener;
  26. import com.yaomei.set.R;
  27. public class PreferenceScreenExt extends PreferenceGroup implements
  28.         OnItemClickListener, DialogInterface.OnDismissListener {
  29.     private Dialog dialog;
  30.     private TextView title, summary;
  31.     private RelativeLayout area;
  32.     private ListView listView;
  33.     List<Preference> list;
  34.     private List<HashMap<String, String>> listStr;
  35.     private CharSequence[] mEntries;
  36.     private String mValue;
  37.     private SimpleAdapter simple;
  38.     private static final int MSG_BIND_PREFERENCES = 0;
  39.     private Handler mHandler = new Handler() {
  40.         @Override
  41.         public void handleMessage(Message msg) {
  42.             switch (msg.what) {
  43.             case MSG_BIND_PREFERENCES:
  44.                 setValue(mValue);
  45.                 break;
  46.             }
  47.         }
  48.     };
  49.     public PreferenceScreenExt(Context context, AttributeSet attrs) {
  50.         this(context, attrs, android.R.attr.preferenceScreenStyle);
  51.         // TODO Auto-generated constructor stub
  52.     }
  53.     public PreferenceScreenExt(Context context, AttributeSet attrs, int defStyle) {
  54.         super(context, attrs, android.R.attr.preferenceScreenStyle);
  55.         // TODO Auto-generated constructor stub
  56.         int resouceId = attrs.getAttributeResourceValue(null, "Entries", 0);
  57.         if (resouceId > 0) {
  58.             mEntries = getContext().getResources().getTextArray(resouceId);
  59.         }
  60.     }
  61.     @Override
  62.     protected void onBindView(View view) {
  63.         // TODO Auto-generated method stub
  64.         area = (RelativeLayout) view.findViewById(R.id.area);
  65.         title = (TextView) view.findViewById(R.id.title);
  66.         summary = (TextView) view.findViewById(R.id.summary);
  67.         title.setText(getTitle());
  68.         summary.setText(getPersistedString(getSummary().toString()));
  69.         area.setOnClickListener(new OnClickListener() {
  70.             @Override
  71.             public void onClick(View v) {
  72.                 // TODO Auto-generated method stub
  73.                 showDialog();
  74.             }
  75.         });
  76.     }
  77.     @Override
  78.     protected View onCreateView(ViewGroup parent) {
  79.         // TODO Auto-generated method stu
  80.         View view = LayoutInflater.from(getContext()).inflate(
  81.                 R.layout.preference_screen, parent, false);
  82.         return view;
  83.     }
  84.     public void bindView(ListView listview) {
  85.         int length = mEntries.length;
  86.         int i = 0;
  87.         listStr = new ArrayList<HashMap<String, String>>();
  88.         for (i = 0; i < length; i++) {
  89.             HashMap<String, String> map = new HashMap<String, String>();
  90.             map.put("keyname", mEntries[i].toString());
  91.             listStr.add(map);
  92.         }
  93.         simple = new SimpleAdapter(getContext(), listStr, R.layout.dialog_view,
  94.                 new String[] { "keyname" }, new int[] { R.id.text });
  95.         listview.setAdapter(simple);
  96.         listview.setOnItemClickListener(this);
  97.     }
  98.     public void showDialog() {
  99.         listView = new ListView(getContext());
  100.         bindView(listView);
  101.         dialog = new Dialog(getContext(), android.R.style.Theme_NoTitleBar);
  102.         dialog.setContentView(listView);
  103.         dialog.setOnDismissListener(this);
  104.         dialog.show();
  105.     }
  106.     @Override
  107.     public void onItemClick(AdapterView<?> parent, View view, int position,
  108.             long id) {
  109.         // TODO Auto-generated method stub
  110.         mValue = listStr.get(position).get("keyname").toString();
  111.         persistString(mValue);
  112.         callChangeListener(mValue);
  113.         dialog.dismiss();
  114.     }
  115.     @Override
  116.     public void onDismiss(DialogInterface dialog) {
  117.         // TODO Auto-generated method stub
  118.     }
  119.     private OnPreferenceChangeListener temp;
  120.     public interface OnPreferenceChangeListener {
  121.         public boolean onPreferenceChange(Preference preference, Object newValue);
  122.     }
  123.     public void setOnPreferenceChangeListener(
  124.             OnPreferenceChangeListener preference) {
  125.         this.temp = preference;
  126.     }
  127.     public void setValue(String value) {
  128.         summary.setText(value);
  129.     }
  130.     public boolean callChangeListener(Object newValue) {
  131.         return temp == null ? true : temp.onPreferenceChange(this, newValue);
  132.     }
  133.     public void postBindPreferences() {
  134.         if (mHandler.hasMessages(MSG_BIND_PREFERENCES))
  135.             return;
  136.         mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
  137.     }
  138. }

复制代码
然后在preferenceActivity 界面在回调函数:onPreferenceChange调用postBindPreferences即可更新。
Tip:这里的onPreferenceChange  调用postBindPreferences 不是必须的,你同样可以在内部里面实现,通过执行某一操作发送消息也可。
好了,在这里我要感谢那几位朋友对我的帮助,提出了很多宝贵的意见。谢谢。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个自定义Preference布局的示例代码,包含一个Button按钮并实现了点击事件: 首先,在res/layout目录下创建一个名为custom_preference.xml的布局文件,代码如下: ```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:gravity="center_vertical" android:paddingEnd="?android:attr/scrollbarSize"> <!-- Preference icon --> <ImageView android:id="@+android:id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="10dp" android:layout_gravity="center_vertical" android:contentDescription="@null" /> <!-- Preference title and summary --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+android:id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLargeInverse" android:textColor="?android:attr/textColorPrimaryInverse" android:singleLine="true" android:ellipsize="end" android:textStyle="bold" android:paddingTop="5dp" /> <TextView android:id="@+android:id/summary" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:textColor="?android:attr/textColorSecondaryInverse" android:maxLines="3" android:ellipsize="end" android:paddingBottom="5dp" /> </LinearLayout> <!-- Custom button --> <Button android:id="@+id/custom_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Custom Button" android:layout_marginEnd="10dp" android:onClick="onButtonClicked" /> </LinearLayout> ``` 其中,我们添加了一个Button按钮,设置了其ID为custom_button,并在其中添加了一个onClick属,指向一个名为onButtonClicked的方法。 接着,在我们的Preference类中,重写onBindViewHolder方法,以及实现onButtonClicked方法,完整代码如下: ```java public class CustomPreference extends Preference { public CustomPreference(Context context, AttributeSet attrs) { super(context, attrs); setLayoutResource(R.layout.custom_preference); } @Override public void onBindViewHolder(PreferenceViewHolder holder) { super.onBindViewHolder(holder); // Get the custom button view Button button = (Button) holder.findViewById(R.id.custom_button); // Set the click listener for the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Do something when the button is clicked Toast.makeText(getContext(), "Custom button clicked", Toast.LENGTH_SHORT).show(); } }); } // Custom button click handler public void onButtonClicked(View view) { // Do something when the button is clicked Toast.makeText(getContext(), "Custom button clicked", Toast.LENGTH_SHORT).show(); } } ``` 在该类中,我们重写了onBindViewHolder方法,通过ViewHolder获取了我们自定义布局中的Button,并设置了其点击事件。同时,我们还实现了一个名为onButtonClicked的方法,用于处理Button的点击事件。 最后,在我们的PreferenceActivity或PreferenceFragment中,添加我们自定义的Preference: ```xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Custom Preference Category"> <com.example.myapplication.CustomPreference android:key="custom_preference" android:title="Custom Preference" android:summary="This is a custom preference with a button" /> </PreferenceCategory> </PreferenceScreen> ``` 这样就完成了一个自定义Preference布局,并添加了一个Button按钮并实现了点击事件的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值