Search code examples
androidandroid-custom-view

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>

When I want to add this view programmatically, How to do this?

MainActivity.java:

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

I don't know how to add app:play_anim="@raw/icon_home" this part.


Solution

  • You should have a function on your custom view like

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

    then you can call from code like

    interactiveImageView.setPlayAnim(R.raw.somthing)