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

相关文章

IDEA和GIT关于文件中LF和CRLF问题及解决

《IDEA和GIT关于文件中LF和CRLF问题及解决》文章总结:因IDEA默认使用CRLF换行符导致Shell脚本在Linux运行报错,需在编辑器和Git中统一为LF,通过调整Git的core.aut... 目录问题描述问题思考解决过程总结问题描述项目软件安装shell脚本上git仓库管理,但拉取后,上l

解决docker目录内存不足扩容处理方案

《解决docker目录内存不足扩容处理方案》文章介绍了Docker存储目录迁移方法:因系统盘空间不足,需将Docker数据迁移到更大磁盘(如/home/docker),通过修改daemon.json配... 目录1、查看服务器所有磁盘的使用情况2、查看docker镜像和容器存储目录的空间大小3、停止dock

idea npm install很慢问题及解决(nodejs)

《ideanpminstall很慢问题及解决(nodejs)》npm安装速度慢可通过配置国内镜像源(如淘宝)、清理缓存及切换工具解决,建议设置全局镜像(npmconfigsetregistryht... 目录idea npm install很慢(nodejs)配置国内镜像源清理缓存总结idea npm in

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

idea突然报错Malformed \uxxxx encoding问题及解决

《idea突然报错Malformeduxxxxencoding问题及解决》Maven项目在切换Git分支时报错,提示project元素为描述符根元素,解决方法:删除Maven仓库中的resolv... 目www.chinasem.cn录问题解决方式总结问题idea 上的 maven China编程项目突然报错,是

在Ubuntu上打不开GitHub的完整解决方法

《在Ubuntu上打不开GitHub的完整解决方法》当你满心欢喜打开Ubuntu准备推送代码时,突然发现终端里的gitpush卡成狗,浏览器里的GitHub页面直接变成Whoathere!警告页面... 目录一、那些年我们遇到的"红色惊叹号"二、三大症状快速诊断症状1:浏览器直接无法访问症状2:终端操作异常

mybatis直接执行完整sql及踩坑解决

《mybatis直接执行完整sql及踩坑解决》MyBatis可通过select标签执行动态SQL,DQL用ListLinkedHashMap接收结果,DML用int处理,注意防御SQL注入,优先使用#... 目录myBATiFBNZQs直接执行完整sql及踩坑select语句采用count、insert、u

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

MyBatis Plus大数据量查询慢原因分析及解决

《MyBatisPlus大数据量查询慢原因分析及解决》大数据量查询慢常因全表扫描、分页不当、索引缺失、内存占用高及ORM开销,优化措施包括分页查询、流式读取、SQL优化、批处理、多数据源、结果集二次... 目录大数据量查询慢的常见原因优化方案高级方案配置调优监控与诊断总结大数据量查询慢的常见原因MyBAT