如何以编程方式将值传递给我的CustomView?

时间:2019-06-27 11:09:27

标签: android android-custom-view

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="InteractiveImageView">
        <attr name="play_anim" format="reference|integer" />
    </declare-styleable>
</resources>

使用示例(activity_main)。xml

<com.doitandroid.mylottie.InteractiveImageView
    app:play_anim="@raw/icon_home">

</com.doitandroid.mylottie.InteractiveImageView>

当我要以编程方式添加此视图时,该怎么做?

MainActivity.java

LinearLayout linearLayout = findViewById(R.id.main_ll);
InteractiveImageView interactiveImageView = new InteractiveImageView(this);
linearLayout.addView(interactiveImageView);

我不知道如何添加app:play_anim="@raw/icon_home"这部分。

2 个答案:

答案 0 :(得分:2)

您应该具有以下形式的构造函数:

    public InteractiveImageView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    loadAttributes(attrs); //Here use the attributes.
}

使用AttributeSet传递您的值。

示例:

    private void loadAttributes(AttributeSet attrs) {
    if (attrs != null) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.AudioPlayerView);
        mBackgroundDrawable = typedArray.getDrawable(R.styleable.AudioPlayerView_player_background);
    }
}

答案 1 :(得分:1)

您应该在自定义视图中具有以下功能

public void setPlayAnim(@RawRes int playAnim) {
        // do something 
}

然后您可以通过

之类的代码进行调用
interactiveImageView.setPlayAnim(R.raw.somthing)