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

本文主要是介绍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 不是必须的,你同样可以在内部里面实现,通过执行某一操作发送消息也可。
好了,在这里我要感谢那几位朋友对我的帮助,提出了很多宝贵的意见。谢谢。

这篇关于Android 完美解决自定义preference与ActivityGroup UI更新的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/681860

相关文章

详谈redis跟数据库的数据同步问题

《详谈redis跟数据库的数据同步问题》文章讨论了在Redis和数据库数据一致性问题上的解决方案,主要比较了先更新Redis缓存再更新数据库和先更新数据库再更新Redis缓存两种方案,文章指出,删除R... 目录一、Redis 数据库数据一致性的解决方案1.1、更新Redis缓存、删除Redis缓存的区别二

oracle数据库索引失效的问题及解决

《oracle数据库索引失效的问题及解决》本文总结了在Oracle数据库中索引失效的一些常见场景,包括使用isnull、isnotnull、!=、、、函数处理、like前置%查询以及范围索引和等值索引... 目录oracle数据库索引失效问题场景环境索引失效情况及验证结论一结论二结论三结论四结论五总结ora

element-ui下拉输入框+resetFields无法回显的问题解决

《element-ui下拉输入框+resetFields无法回显的问题解决》本文主要介绍了在使用ElementUI的下拉输入框时,点击重置按钮后输入框无法回显数据的问题,具有一定的参考价值,感兴趣的... 目录描述原因问题重现解决方案方法一方法二总结描述第一次进入页面,不做任何操作,点击重置按钮,再进行下

解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题

《解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题》本文主要讲述了在使用MyBatis和MyBatis-Plus时遇到的绑定异常... 目录myBATis-plus-boot-starpythonter与mybatis-spring-b

Android数据库Room的实际使用过程总结

《Android数据库Room的实际使用过程总结》这篇文章主要给大家介绍了关于Android数据库Room的实际使用过程,详细介绍了如何创建实体类、数据访问对象(DAO)和数据库抽象类,需要的朋友可以... 目录前言一、Room的基本使用1.项目配置2.创建实体类(Entity)3.创建数据访问对象(DAO

电脑显示hdmi无信号怎么办? 电脑显示器无信号的终极解决指南

《电脑显示hdmi无信号怎么办?电脑显示器无信号的终极解决指南》HDMI无信号的问题却让人头疼不已,遇到这种情况该怎么办?针对这种情况,我们可以采取一系列步骤来逐一排查并解决问题,以下是详细的方法... 无论你是试图为笔记本电脑设置多个显示器还是使用外部显示器,都可能会弹出“无HDMI信号”错误。此消息可能

mysql主从及遇到的问题解决

《mysql主从及遇到的问题解决》本文详细介绍了如何使用Docker配置MySQL主从复制,首先创建了两个文件夹并分别配置了`my.cnf`文件,通过执行脚本启动容器并配置好主从关系,文中还提到了一些... 目录mysql主从及遇到问题解决遇到的问题说明总结mysql主从及遇到问题解决1.基于mysql

如何测试计算机的内存是否存在问题? 判断电脑内存故障的多种方法

《如何测试计算机的内存是否存在问题?判断电脑内存故障的多种方法》内存是电脑中非常重要的组件之一,如果内存出现故障,可能会导致电脑出现各种问题,如蓝屏、死机、程序崩溃等,如何判断内存是否出现故障呢?下... 如果你的电脑是崩溃、冻结还是不稳定,那么它的内存可能有问题。要进行检查,你可以使用Windows 11

如何安装HWE内核? Ubuntu安装hwe内核解决硬件太新的问题

《如何安装HWE内核?Ubuntu安装hwe内核解决硬件太新的问题》今天的主角就是hwe内核(hardwareenablementkernel),一般安装的Ubuntu都是初始内核,不能很好地支... 对于追求系统稳定性,又想充分利用最新硬件特性的 Ubuntu 用户来说,HWEXBQgUbdlna(Har

Ubuntu 24.04 LTS怎么关闭 Ubuntu Pro 更新提示弹窗?

《Ubuntu24.04LTS怎么关闭UbuntuPro更新提示弹窗?》Ubuntu每次开机都会弹窗提示安全更新,设置里最多只能取消自动下载,自动更新,但无法做到直接让自动更新的弹窗不出现,... 如果你正在使用 Ubuntu 24.04 LTS,可能会注意到——在使用「软件更新器」或运行 APT 命令时,