nrofis
nrofis

Reputation: 9776

ListView as navigations menu

I am trying to implements menu (open activities and dialogs) in list in my application, like other applications that did this before (like the "categories" list on Google Play, and many more). I have notice that it is not a simple thing as I thought.

What I have thought about is to create two lists, one for the actions names, second for the icon. Then use SimpleAdapter to connect them to the items on the list. And on the onItemClicked event, to do a huge switch-case segment, and perform the action each item need to do.

I don't think that is the correct way to do it. There are different ways (and simpler) to do that?

Upvotes: 0

Views: 51

Answers (1)

Dmitry Nelepov
Dmitry Nelepov

Reputation: 7306

Yes, you may:

1.Use reflections for calling methods - and set method as tag of your items. And then item cliked get Method from tag of View.

1.1.Or u can use String names of methods and then call whem my code:

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.For this best way use BaseAdapter and use own type of items (like

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

3.Also u can use SimpleAdapter with one hidden textView in your XML layout of items. And then item is clicked get from this hidden textView name of method (as String). Ofcourse before you will need set for this textView name of method.

It will like:

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);

Upvotes: 1

Related Questions