gpt4 book ai didi

java - 从导航 View (抽屉)动态检索对象 android/java

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:11 24 4
gpt4 key购买 nike

我再次陷入编码困境,从无所不知的 StackOverflow 社区寻求知识......我的问题很简单。我已经用对象填充了导航 View 抽屉。这些对象的 toString() 方法已被覆盖,以在列表中显示每个对象自己的名称。单击抽屉列表中的每个对象都会显示一条警报消息,其中应显示(“您单击了”+ myDrawerObject.getName())问题出在 onNavigationItemSelected 监听器中。此方法返回一个 MenuItem 项目,它是一个 View 。我无法理解为什么我不能像对待它应该包含的对象一样对待这个 View 。非常感谢您的帮助,并提前致谢!

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

我尝试将项目值转换回对象,但无济于事 MyObject myObject = (MyObject)项目;//Item 仍然是一个 View ,并且 View 似乎无法转换为对象

我什至尝试将所有创建的 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++;
}

关于java - 从导航 View (抽屉)动态检索对象 android/java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com