0

I have an "ADD" button which when pressed should add a new item to the side navigation drawer. I already have two items in the drawer and want to add 1 item every time the "ADD" button is pressed. How do I do that?

1 Answers1

0

first create a nav_view for you want your navigation drawer to be looked like : nav_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
        <include
                android:id="@+id/header"
                layout="@layout/your_nav_header"
                android:layout_width="match_parent"
                android:layout_height="176dp"/>

        <ScrollView
                android:id="@+id/scrollView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/tvVersion"
                android:layout_below="@+id/header">

            <LinearLayout
                    android:id="@+id/dynamically_added_items"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="right"
                    android:orientation="vertical"/>

        </ScrollView>
    </RelativeLayout>

then in your view :

val li = LayoutInflater.from(context)
val mainView = li.inflate(R.layout.nav_drawer, null)
val linearLayout = mainView.findViewById<LinearLayout>(R.id.dynamically_added_items)

items.forEach {
    val navItem = MyNavigationItem(li)
    linearLayout.addView(navItem.getView())
}

which items are list of items you want to add to your drawer, this could be a list or just one item like below :

val navItem = MyNavigationItem(li)
linearLayout.addView(navItem.getView())

which MyNavigationItem is a class for setting the view for each item in drawer :

class NavigationItemWidget(
    item: MyItem,
    li: LayoutInflater
) {

    private val mainView = li.inflate(R.layout.item_nav, null)

    fun getView(): View {
        mainView.setOnClickListener {

        }
    }

}

in the above class by getView() function setup the view for your custom item_nav layout.

Bita Mirshafiee
  • 600
  • 8
  • 14