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编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

mybatis和mybatis-plus设置值为null不起作用问题及解决

《mybatis和mybatis-plus设置值为null不起作用问题及解决》Mybatis-Plus的FieldStrategy主要用于控制新增、更新和查询时对空值的处理策略,通过配置不同的策略类型... 目录MyBATis-plusFieldStrategy作用FieldStrategy类型每种策略的作

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

linux下多个硬盘划分到同一挂载点问题

《linux下多个硬盘划分到同一挂载点问题》在Linux系统中,将多个硬盘划分到同一挂载点需要通过逻辑卷管理(LVM)来实现,首先,需要将物理存储设备(如硬盘分区)创建为物理卷,然后,将这些物理卷组成... 目录linux下多个硬盘划分到同一挂载点需要明确的几个概念硬盘插上默认的是非lvm总结Linux下多

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

pip install jupyterlab失败的原因问题及探索

《pipinstalljupyterlab失败的原因问题及探索》在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它... 目录背景问题解决方案总结背景最近在学习Yolo模型,然后其中要下载jupyter(有点LSVmu像一个

Goland debug失效详细解决步骤(合集)

《Golanddebug失效详细解决步骤(合集)》今天用Goland开发时,打断点,以debug方式运行,发现程序并没有断住,程序跳过了断点,直接运行结束,网上搜寻了大量文章,最后得以解决,特此在这... 目录Bug:Goland debug失效详细解决步骤【合集】情况一:Go或Goland架构不对情况二:

解决jupyterLab打开后出现Config option `template_path`not recognized by `ExporterCollapsibleHeadings`问题

《解决jupyterLab打开后出现Configoption`template_path`notrecognizedby`ExporterCollapsibleHeadings`问题》在Ju... 目录jupyterLab打开后出现“templandroidate_path”相关问题这是 tensorflo

如何解决Pycharm编辑内容时有光标的问题

《如何解决Pycharm编辑内容时有光标的问题》文章介绍了如何在PyCharm中配置VimEmulator插件,包括检查插件是否已安装、下载插件以及安装IdeaVim插件的步骤... 目录Pycharm编辑内容时有光标1.如果Vim Emulator前面有对勾2.www.chinasem.cn如果tools工

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干