文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Android 完美解决自定义preference..

Android 完美解决自定义preference..

时间:2010-10-07  来源:terry_龙

之前发过一篇有关于自定义preference 在ActivityGroup 的包容下出现UI不能更新的问题,当时还以为是Android 的一个BUG 现在想想真可笑 。其实是自己对机制的理解不够深刻,看来以后要多看看源码才行。

本篇讲述内容大致为如何自定义preference 开始到与ActivityGroup 互用下UI更新的解决方法。

首先从扩展preference开始:

类文件必须继承自Preference并实现构造函数,这里我一般实现两个构造函数分别如下(类名为:test):

 

    public test(Context context) {
        this(context, null);
        // TODO Auto-generated constructor stub
    }

    public test(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

 

这里第二个构造函数第二个参数为可以使用attrs 为我们自定义的preference 添加扩展的注册属性,比如我们如果希望为扩展的preference 添加一个数组引用,就可使用如下代码:

 

int resouceId = attrs.getAttributeResourceValue(null, "Entries", 0);
        if (resouceId > 0) {
            mEntries = getContext().getResources().getTextArray(resouceId);
        }

 

 

这里的mEntries 是头部声明的一个数组,我们可以在xml文件通过 Entries=数组索引得到一个数组。在这里不深入为大家示范了。

我们扩展preference 有时想让其UI更丰富更好看,这里我们可以通过引用一个layout 文件为其指定UI,可以通过实现如下两个回调函数:

 

@Override
    protected View onCreateView(ViewGroup parent) {
        // TODO Auto-generated method stub
        return LayoutInflater.from(getContext()).inflate(
                R.layout.preference_screen, parent, false);
    }

 

此回调函数与onBindView 一一对应,并优先执行于onBindView ,当创建完后将得到的VIEW返回出去给onBindView处理,如下代码:

 

@Override
    protected void onBindView(View view) {
        // TODO Auto-generated method stub
        super.onBindView(view);
        canlendar = Calendar.getInstance();
        layout = (RelativeLayout) view.findViewById(R.id.area);
        title = (TextView) view.findViewById(R.id.title);
        summary = (TextView) view.findViewById(R.id.summary);
        layout.setOnClickListener(this);
        title.setText(getTitle());
        summary.setText(getPersistedString(canlendar.get(Calendar.YEAR) + "/"
                + (canlendar.get(Calendar.MONTH) + 1) + "/"
                + canlendar.get(Calendar.DAY_OF_MONTH)));

    }

 

 

Tip:onBindView 不是必须的,可以将onBindView 里的处理代码在onCreateView 回调函数一并完成然后返回给onBindView ,具体怎么写看自己的代码风格吧。我个人比较喜欢这种写法,比较明了。

下面我们来了解一下我扩展preference 比较常用到的几个方法:

相关阅读 更多 +
排行榜 更多 +
无限Fps

无限Fps

飞行射击 下载
幸存者时间僵尸

幸存者时间僵尸

飞行射击 下载
金属兄弟Metal Brother

金属兄弟Metal Brother

冒险解谜 下载