开发者

Building a menu with a ListView

My app has a main menu, and I am using a ListView to represent it. Since it's a menu, I will be implementing actions based on which item a user clicks on.

My current implementation looks like this:

  • In strings.xml, I have a string array of the names of the menu items.
  • In the main menu's activity, I inflate the string array: itemList = getResources().getStringArray(R.array.main_menu_array); (itemList is a static String[])
  • Then I set an adapter for the ListView: listView.setAdapter(new ArrayAdapter<String>(this, R.layout.main_menu_item, itemList)); (R.layout.main_menu_item specifies the layout for each individual menu item. It basically is just a TextView with a couple of attributes.)
  • I set up an OnItemClickListener fo开发者_JS百科r the ListView.

The anonymous OnItemClickListener class implements onItemClick() like this

public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    switch (position) {
    case POS_ITEM_A:
        ... break;
    case POS_ITEM_B:
        ... break;
    }
}

POS_ITEM_A and POS_ITEM_B are final static variables set to 0 and 1 respectively.

I don't think this is good code. How can I fix it?


You could do that with a spinner but the code will be almost the same.

Another alternative, simpler but that is less extensible is to work with AlertDialog.Buidler and use the setMultipleChoices method. Or this general documentation page.

But a listview is not that bad. For a small feature, I suggest the dialog builder, for manipulating the main objects of your app, use a list view or spinner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜