# Zur Laufzeit erstelltes MenuItem an eine View binden



## werdas34 (21. Dez 2021)

Hallo,

fürs Studium soll in Kürze eine Einkaufszettel in Appform erstellt werden. Dazu soll zur Laufzeit neue Listen angelegt werden bzw aus der DB die Listenstruktur aufgebaut werden. -> Problem: MenuItem Struktur nicht im Vorfeld bekannt.

Meine Idee war es den NavigationDrawer als Fundament zu nutzen. Und mittels MenuItem "Neue Liste erstellen", dann zur Laufzeit ein neues MenuItem "Liste #1" zu erstellen. Auf Klick diesen Items gelangt man auf die Listenansicht über Arrayadapter.

Das erzeugen des MenuItems zur Laufzeit funktioniert. Nur ist da keine View/Layout angebunden. Und alles was ich im Internet finde setzt auf bereits bekannte Menustruktur auf. Ich weiß nicht wie man das nennt. Mir fehlt offenbar das entscheidende Keyword zum suchen. inflate?

Hier mal meine MainActivty:

```
public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;

    private Menu menu;

    private TextView mName;
    private TextView mEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);
        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Add Entry fragment

                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        View headerLayout = navigationView.getHeaderView(0);
        mName = headerLayout.findViewById(R.id.textName);
        mEmail = headerLayout.findViewById(R.id.textEmail);

        MainViewModel mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
        mainViewModel.getUser().observe(this, new Observer<User>() {
            @Override
            public void onChanged(@Nullable User user) {
                mName.setText(user.getName());
                mEmail.setText(user.getEmail());
            }
        });

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Menu menu = navigationView.getMenu();
                int menuSize = menu.size();

                switch(item.getItemId()){
                    case R.id.menu_signOut:
                        signOut();
                        return true;

                    case R.id.menu_addNewList:
                        // Liste erstellen
                        //groupId, itemId, order, text
                        menu.add(R.id.menu_lists, menuSize, 0, "Test " + menuSize);
                        menu.findItem(menuSize).setIcon(R.drawable.ic_list);

                        Toast.makeText(MainActivity.this, "Neue Liste erstellt", Toast.LENGTH_SHORT).show();
                        drawer.closeDrawers();
                        return true;
                }
                return false;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    private void signOut(){
        FirebaseAuth.getInstance().signOut();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }
}
```

activity_main_drawer.xml

```
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">


    <group
        android:id="@+id/menu_lists"
        android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:orderInCategory="0"
            android:icon="@drawable/ic_menu_camera"
            android:title="@string/menu_home" />
        <item
            android:id="@+id/nav_gallery"
            android:orderInCategory="0"
            android:icon="@drawable/ic_menu_gallery"
            android:title="@string/menu_gallery" />
        <item
            android:id="@+id/nav_slideshow"
            android:orderInCategory="0"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="@string/menu_slideshow" />
    </group>

    <group android:checkableBehavior="none">
        <item
            android:id="@+id/menu_addNewList"
            android:orderInCategory="1"
            android:icon="@drawable/ic_add_list"
            android:title="@string/neue_liste_erstellen" />
    </group>

    <group
        android:id="@+id/menu_bottom"
        android:checkableBehavior="none">

        <item
            android:id="@+id/menu_signOut"
            android:orderInCategory="2"
            android:icon="@drawable/ic_logout"
            android:title="@string/abmelden" />
    </group>

</menu>
```

Der Rest müsste noch so sein, wie das NavigationDrawer-Template von AndroidStudio.
Oft sehe ich das der Anfang der Activity so ungefähr aussieht: 
Ich weiß nicht ob diese AppBarConfiguration für meinen dynamischen Fall geeignet ist.

[CODE lang="java"] public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    // Make sure to be using androidx.appcompat.app.ActionBarDrawerToggle version.
    private ActionBarDrawerToggle drawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // This will display an Up icon (<-), we will replace it with hamburger later
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    }[/CODE]

Wie ich binde ich an eine zur Laufzeit erstellte MenuItem an eine View?

mfg werdas34


----------



## osion (15. Jan 2022)

Schon lange her, aber dir fehlt ein Adapter:

```
/**
 * Adapter for the reservation items
 */
public class ReservationAdapter extends RecyclerView.Adapter<ReservationAdapter.ItemHolder> {

  private List<Reservation> mItemList = new ArrayList<>();
  private OnItemClickListener mListener;

  @NonNull
  @Override
  public ReservationAdapter.ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
        .inflate(R.layout.reservation_item, parent, false);
    return new ReservationAdapter.ItemHolder(itemView, mListener);
  }


  @Override
  public void onBindViewHolder(@NonNull ItemHolder holder, int position) {
    Reservation item = mItemList.get(position);
    holder.mArticleTitle.setText(
        item.getResourceName()
    );
    holder.mDateTimeRange.setText(
        convertForFrontend(item.getStartDate())
            + " - "
            + convertForFrontend(item.getEndDate())
    );
    holder.mTitle.setText(
        item.getTitle()
    );
    holder.mDescription.setText(
        item.getDescription()
    );
    holder.mPersonName.setText(
        item.getFirstName() + " " + item.getLastName()
    );
    holder.mReferenceNumber = item.getReferenceNumber();
    holder.mStartDate = new DateTime(
        item.getStartDate()
    );
    holder.mEndDate = new DateTime(
        item.getEndDate()
    );


  }

  @Override
  public int getItemCount() {
    return mItemList.size();
  }

  static class ItemHolder extends RecyclerView.ViewHolder {

    private TextView mArticleTitle;
    private TextView mTitle;
    private TextView mDescription;
    private TextView mDateTimeRange;
    private TextView mPersonName;
    private String mReferenceNumber;
    private DateTime mStartDate;
    private DateTime mEndDate;

    ItemHolder(@NonNull View itemView,
        OnItemClickListener listener) {
      super(itemView);
      mArticleTitle = itemView.findViewById(R.id.textView_reservation_article_name);
      mTitle = itemView.findViewById(R.id.textView_reservation_title);
      mDescription = itemView.findViewById(R.id.textview_description);
      mDateTimeRange = itemView.findViewById(R.id.textView_timerange);
      mPersonName = itemView.findViewById(R.id.textView_reservation_name);

      itemView.setOnClickListener(reservation -> {
        if (listener != null) {
          int position = getAdapterPosition();
          if (position != RecyclerView.NO_POSITION) {
            listener.onItemClick(
                position,
                mReferenceNumber,
                mStartDate,
                mEndDate
            );
          }
        }
      });
    }
  }

  /**
   * Replace the item list
   */
  void setItems(List<Reservation> reservationList) {
    mItemList = reservationList;
    notifyDataSetChanged();
  }

  /**
   * If a item is clicked then  the listener will be notified
   */
  void setOnItemClickListener(OnItemClickListener listener) {
    this.mListener = listener;
  }

  public interface OnItemClickListener extends ResourcesAdapter.OnItemClickListener {

    void onItemClick(int position, String referenceId, DateTime startDate, DateTime endDate);
  }
}
```


----------

