【问题标题】:ListView as navigations menuListView 作为导航菜单
【发布时间】:2013-06-10 18:51:40
【问题描述】:

我正在尝试在我的应用程序的列表中实现菜单(打开活动和对话框),就像以前这样做的其他应用程序一样(例如 Google Play 上的“类别”列表等等)。我注意到这并不像我想象的那样简单。

我想到的是创建两个列表,一个用于操作名称,第二个用于图标。然后使用SimpleAdapter 将它们连接到列表中的项目。而在onItemClicked事件上,做一个巨大的switch-case段,并执行每个项目需要做的动作。

我认为这不是正确的做法。有不同的方法(并且更简单)可以做到这一点?

【问题讨论】:

    标签: android list android-activity


    【解决方案1】:

    是的,您可以:

    1.使用反射调用方法 - 并将方法设置为项目的标签。然后item点击get Method from tag of View。

    1.1.或者你可以使用方法的字符串名称,然后调用我的代码:

    public static Object makeNativeApiFunctionCall(Object target, String functionName, Object... parameters) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            Object responseObject;
            Method method = target.getClass().getMethod(functionName, parameters.getClass());
            responseObject = method.invoke(target, new Object[]{parameters});
            return responseObject;
        }
    

    2.对于这种最佳方式,请使用 BaseAdapter 并使用自己的项目类型(如

    class MyListMenuItem{
      String methodName;
      String title;
      Integer imgResource;
    }
    

    3.您还可以在您的 XML 项目布局中使用 SimpleAdapter 和一个隐藏的 textView。然后从这个隐藏的 textView 方法名称(作为字符串)中单击项目。当然,在此之前您需要设置此 textView 方法的名称。

    它会喜欢:

    String[] texts = { "sometext 1", "sometext 2" };
    int[] images = { R.id.img1, R.id.img2};
    String methods={"Method1","Method2"};
    
    ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
        texts.length);
    Map<String, Object> m;
    for (int i = 0; i < texts.length; i++) {
      m = new HashMap<String, Object>();
      m.put(ATTRIBUTE_NAME_TEXT, texts[i]);
      m.put(ATTRIBUTE_NAME_METHOD, methods[i]);
      m.put(ATTRIBUTE_NAME_IMAGE, images[i]);
      data.add(m);
    }
    
    String[] from = { ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_METHOD,
        ATTRIBUTE_NAME_IMAGE };
    int[] to = { R.id.tvText, R.id.hiddenTextView, R.id.ivImg };
    
    SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.item,
        from, to);
    
    lvSimple = (ListView) findViewById(R.id.lvSimple);
    lvSimple.setAdapter(sAdapter);
    

    【讨论】:

    • 非常好!但是如果没有在代码上定义三个数组,有没有办法做到这一点? (我试图以最通用的方式来做)
    • 是的,MVC 工作正常 :) 在我的例子中 M - 是代码,你可以使用 else。你想要吗?来自互联网? XML 布局?还是等等?
    猜你喜欢
    • 2023-01-09
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多