gian848396 gian848396 - 4 months ago 11
Android Question

How do I open specific activities when selecting from an array in a navigation drawer?

I'm trying to figure out the right way to implement this feature into this algorithm. I would like to be able to open a specific activity for "Log History", "New Log", "Analytics", "Settings".

private void addDrawerItems() {
String[] osArray = { "Log History", "New Log", "Analytics", "Settings"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);

mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewLogActivity.class);
startActivity(intent);
}
});
}

Answer

Assuming you never change your array,

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    switch (position) {
    case 0: //Log History
        startActivity(this, LogHistory.class);
        break;
    case 1: //Log History
        startActivity(this, NewLog.class);
        break;
    case 2: //Log History
        startActivity(this, Analytics.class);
        break;
    case 3: //Log History
        startActivity(this, Settings.class);
        break;
    default:
        throw new InvalidArgumentException("wtf, unknown position");
    }
}

I can't remember if position starts at 0 or 1, but it should give you an idea of what to do.

Comments