Search code examples
androidxmlmenuitembottomnavigationviewlottie

How to set Lottie file to menu item?


I am creating a bottom navigation and the icon needs to be an animated Lottie file. It seems it's not possible to write a binding adapter for the tag. Is there any solution that allows us to have lottie animations in bottom nav?

<item
    android:id="@+id/my_navigation"
    android:icon="@drawable/my_icon"
    android:title="@string/my_text" 
    **app:setLottie=@raw/my_file/>**

Solution

  • First of all create a custom layout, in this example name it layout_gift

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:orientation="horizontal">
    
        <com.airbnb.lottie.LottieAnimationView
            android:id="@+id/watch_animation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:lottie_autoPlay="true"
            app:lottie_fileName="gift.json"
            app:lottie_loop="true"
            app:lottie_speed="4" />
    
    </LinearLayout>
    

    then set it as;

        <item
        android:id="@+id/action_gift"
        android:orderInCategory="100"
        android:title="@string/gift"
        app:actionLayout="@layout/layout_gift"
        app:showAsAction="always" />
    

    Moreover, clickListener is as below, you can't handle it in onOptionsItemSelected

     @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
     
        inflater.inflate(R.menu.main, menu);
    
        MenuItem giftItem = menu.findItem(R.id.action_gift);
        View giftView = giftItem.getActionView();
        giftView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // todo
            }
        });
    }