如何以编程方式将值传递给我的 CustomView?
How to pass value to my CustomView programmatically?
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="InteractiveImageView">
<attr name="play_anim" format="reference|integer" />
</declare-styleable>
</resources>
usage_example(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"
这部分。
您应该具有以下形式的构造函数:
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);
}
}
您的自定义视图应该有一个函数,例如
public void setPlayAnim(@RawRes int playAnim) {
// do something
}
然后你可以从
这样的代码调用
interactiveImageView.setPlayAnim(R.raw.somthing)
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="InteractiveImageView">
<attr name="play_anim" format="reference|integer" />
</declare-styleable>
</resources>
usage_example(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"
这部分。
您应该具有以下形式的构造函数:
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);
}
}
您的自定义视图应该有一个函数,例如
public void setPlayAnim(@RawRes int playAnim) {
// do something
}
然后你可以从
这样的代码调用interactiveImageView.setPlayAnim(R.raw.somthing)