1

我有一个自定义视图,扩展了 LinearLayout 并尝试添加一些自定义属性,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- other stuff -->
    <declare-styleable name="UIPlayer">
        <attr name="team" format="integer" />
        <attr name="playAnimation" format="reference" />
    </declare-styleable>
</resources>

我的自定义视图是这样的:

public class UIPlayer extends LinearLayout
{    
    // . . .

    public UIPlayer(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        initAttrs(context, attrs);
    }

    public UIPlayer(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        initAttrs(context, attrs);
    }

    public void initAttrs(Context context, AttributeSet attrs)
    {
        TypedArray taPlayer = context.obtainStyledAttributes(attrs, R.styleable.UIPlayer);
        int team = taPlayer.getInt(R.styleable.UIPlayer_team, -1); 
        player.setTeam(team);

        int animPlayId = taPlayer.getResourceId(R.styleable.UIPlayer_playAnimation, -1);
        try
        {    
            animPlay = AnimationUtils.loadAnimation(context, animPlayId);
        }
        catch (NotFoundException e)
        {
            d("anim", "onPlay not found! " + animPlayId);
        }
        taPlayer.recycle();
    }
    // . . .
}

我的布局文件是这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:devn="http://schemas.android.com/apk/res/devN.games.mygame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clipChildren="false"
    android:orientation="vertical"
    android:weightSum="3.0" >

    <devN.games.UIPlayer
        android:id="@+id/player"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:clipChildren="false"
        android:gravity="top"
        devn:playAnimation="@anim/play"
        devn:team="2" >
    </devN.games.UIPlayer>

    <!-- ... -->

</LinearLayout>

我做错了什么,我无法从构造函数中检索动画?(“奇怪的事实”是 team 属性工作正常)

4

1 回答 1

2

经过对android源代码的大量研究,我尝试了重载方法:

obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)

它就像一个魅力!:) 所以正确的代码是:

TypedArray taPlayer = context.obtainStyledAttributes(attrs, R.styleable.UIPlayer, 0, 0);
于 2012-08-14T15:59:22.693 回答