魔术obtainStyledAttributes方法 [英] Magic with obtainStyledAttributes method

查看:169
本文介绍了魔术obtainStyledAttributes方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code:

public class CustomLayoutWithText extends LinearLayout {

    private Context context;
    private AttributeSet attrs;

    public CustomLayoutWithText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.attrs = attrs;
        fooAttrs();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        fooAttrs();
    }

    private void fooAttrs() {
        int[] set = {
            android.R.attr.text        // idx 0
        };
        TypedArray a = context.obtainStyledAttributes(attrs, set);
        Log.d(null, a.getString(0));
    }
}

和XML:

<com.korovyansk.android.views.CustomLayoutWithText
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Some text"/>

合理的期望,结果应该是:
    某些文本
    某些文本

Reasonable to expect that output will be:
Some text
Some text

但它的:
    某些文本
    空

But it's:
Some text
null

为什么第二次出现零?又该如何避免呢?

推荐答案

我觉得 ATTRS 中的所有数据被回收。实际上在例子比比皆是,他们建议明确地回收所有获得类型数组从的AttributeSet 在视图的构造函数。我想你应该遵循最佳实践过。

I think all data in attrs gets recycled. In fact in the examples everywhere they recommend to explicitly recycle all obtained typed arrays from the AttributeSet in constructor of the View. I think you should follow the best practice too.

    TypedArray a = context.obtainStyledAttributes(attrs, set);
    try {
        // read attributes from a
        // ...
    } finally {
        attributes.recycle();
    }

我的猜测是,当 onFinishInflate() ATTRS 已经是空的或不可用。

My guess is that when onFinishInflate() is called, attrs is already empty or unavailable.

在事实上,根据 LayoutInflater 的code时,的AttributeSet 传递到视图构造布局在通货膨胀实际上是基于 XmlPullParser 。该 onFinishInflate()夸大其所有的孩子后,被称为父视图。

In fact, according to the code of LayoutInflater, the AttributeSet that is passed into View constructor during layout inflation is actually based on XmlPullParser. The onFinishInflate() is called on the parent view after inflating all of its children.

它看起来像在这一点上onFinishInflate()',你不能获得来自 ATTRS 你的属性值。特别是如果你有你的布局里的孩子 - 的 ATTRS 将引用同一个解析器,但是解析器的位置将指向最后解析过孩子的属性

It looks like at this point in 'onFinishInflate()' you cannot obtain the values of your attribute from the attrs. Especially if you have children inside your layout - the attrs will reference to the same parser, but the parser's position will point to the attributes of the last parsed child.

这篇关于魔术obtainStyledAttributes方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆