从导航视图(抽屉)中动态检索 OBJECT android/java

Retrieve OBJECT from a navigation View (drawer) dynamically android/java

我又一次陷入了编码轨道,我来无所不知的 Whosebug 社区寻求知识... 我的问题很简单。我用对象填充了导航视图抽屉。这些对象的 toString() 方法已被覆盖以在列表中显示每个对象自己的名称。单击抽屉列表中的每个对象都会显示一条警告消息,其中应显示 ("you clicked "+ myDrawerObject.getName()) 问题出在 onNavigationItemSelected 侦听器中。 此方法 return 是一个 MenuItem 项,它是一个视图。我无法理解为什么我不能将此视图视为它应该包含的对象。非常感谢并提前致谢!

我知道 item 参数是 return 哪个菜单项已被单击,但如果菜单项是一个对象,为什么我不能调用这些对象的方法? 我尝试获取项目 return 值并调用其 getName() 方法,但无济于事。 item.getName(); (我知道该项目是一个视图,因此它没有 "getName()" 方法

我试过将项目值重新转换为对象,但没有成功 我的对象我的对象=(我的对象)项目; //Item 仍然是一个视图并且视图不能被转换成一个看起来像的对象

我什至尝试将所有创建的 MyObject 类型的对象放入静态 arrayList 中,然后尝试匹配 id 也无济于事。 //在 onNavigationItemSelected 侦听器中 int id = item.getItemId()

//somewhere else in the code
 for (anotherMyObject : listOfEveryMyObjectEverMade){
 anotherMyObject.get(id)
 }
/*returns the id of the item in the listview. as i understand a specific id 
is assigned to every item in the list. so if an object has never been in that 
particular list, it wont have that same id
*/

我必须添加抽屉的内容(字符串列表)是动态创建的,因此菜单或 menItems 没有 xml 文件!

我 运行 遇到了非常相似的情况,并且确实封锁了我好几天!

我几乎有 90% 的把握认为一定有出路...

但我个人并没有找到它,所以我转而进行了一项变通:

private void setMenus() {
    int temp = 0;
  //Mine was inside of a fragment, hints the getActivity() call
    NavigationView navView22 = getActivity().findViewById(R.id.navigation_view);
    MenuItem oneItem = navView22.getMenu().findItem(0);
        if (oneItem == null){
        Menu m = navView22.getMenu();
        SubMenu sm0 = m.addSubMenu(
                getResources().getString(R.string.clickToSelectRookies));
        sm0.add(0,
                temp, temp, getResources().getString(R.string.signAllString));
            tempRooks.add(round1.get(0));
  /*I had to create the entire menu dynamically, so I did so by creating 
  subMenus in my menus in numerical order
  I then created an arraylist to hold all my objects in that same order
  though in retrospect I should have just used a HashMap!!
  finally in the onClick I was able to listen for which subMenu item was clicked
   and since the menu's and my arraylist of objects corresponded I then pulled 
  the correct object from my arraylist. I realize this is a little hacky, but 
  hopefully if you do not find the answer you can do this temporarily.
  If you do find a better solution please post so we all can learn. Thank YOU!!

*/ 温度++;

        SubMenu sm1 = m.addSubMenu(
                getResources().getString(R.string.firstRoundPicks));
        for (int x = 0; x < round1.size(); x++) {
            sm1.add(0, temp, temp, round1.get(x).toString());
                tempRooks.add(round1.get(x));
            temp++;
        }