代码之家  ›  专栏  ›  技术社区  ›  Paris B. G.

动态地从导航视图(抽屉)检索Android /Java

  •  1
  • Paris B. G.  · 技术社区  · 7 年前

    再一次陷入死在我的编码轨道,我来从无所不知的StackOverflow社区寻求知识… 我的问题相当简单。我用对象填充了一个导航视图抽屉。这些对象toString()方法已被覆盖,以在列表中显示每个对象的名称。单击抽屉列表中的每个对象都会显示一条警告消息,该消息应该说(“You clicked”+MyDrawerObject.getName())问题出现在OnNavigationItemSelected侦听器中。 此方法返回一个作为视图的menuItem项。我很难理解为什么我不能把这个视图视为它应该包含的对象。非常感谢您的帮助,并提前表示感谢!

    我知道item参数正在返回已单击的菜单项,但如果菜单项是对象,为什么我不能调用这些对象方法? 我试图获取项目返回值并调用它的getname()方法,但没有用。item.getname();(我了解该项是一个视图,因此它没有“getname()”方法

    我试图将项目值重新转换为一个对象,但没有效果 myObject myObject=(myObject)项; //项仍然是一个视图,不能将视图强制转换为对象

    我甚至尝试将所有创建的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文件!

    1 回复  |  直到 7 年前
        1
  •  0
  •   Paris B. G.    6 年前

    我遇到了一个非常相似的情况,实际上封锁了我好几天!

    我几乎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++;
            }