views:

352

answers:

1

I'm working on my first Android project, and I created a menu via the XML method. My activity is pretty basic, in that it loads the main layout (containing a ListView with my String array of options). Here's the code inside my Activity:

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 // allow stuff to happen when a list item is clicked
 ListView ls = (ListView)findViewById(R.id.menu);
 ls.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   // @todo
  }
 });
}

Within the onItemClick callback handler, I'd like to check which item was clicked, and load a new menu based upon that.

Question 1: How do I go about figuring out which item was clicked? I can't find any straightforward examples on retrieving/testing the id value of the clicked item.

Question 2: Once I have the id value, I assume I can just call the setContentView method again to change to another layout containing my new menu. Is that correct?

A: 

I'm working on my first Android project, and I created a menu via the XML method.

Actually, Android has a separate concept of menus, so I'd be a bit wary about describing your UI in those terms.

How do I go about figuring out which item was clicked?

If you are using an ArrayAdapter, the position parameter passed to onItemClick() is the index into your array.

I assume I can just call the setContentView method again to change to another layout containing my new menu. Is that correct?

Yes, though there may be better approaches to the UI that will be more Android-y. Most Android applications do not start off with some sort of multi-layer navigation before you actually get to do something.

CommonsWare