如何在导航抽屉中单击项目时打开新活动

时间:2015-02-25 11:17:21

标签: android android-fragments navigation-drawer

我是Android开发的新手,并且正如预期的那样在导航抽屉中发现一些困难,我想通过点击导航抽屉左侧窗格中显示的项目来打开一个新活动。

即如果单击项目出现在导航栏中,则应该打开一个新活动。

我尝试了以下但不知道相同的

package com.example.demo_data1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class NavDrawer extends Activity {
   String[] menu;
   DrawerLayout dLayout;
   ListView dList;
   ArrayAdapter<String> adapter;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
 setContentView(R.layout.third_page);
    menu = new String[]{"Home","Android","Windows","Linux","Raspberry Pi","WordPress","Videos","Contact Us"};
      dLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
      dList = (ListView) findViewById(R.id.drawerList);
      adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
      dList.setAdapter(adapter);
      dList.setSelector(android.R.color.holo_blue_dark);
      dList.setOnItemClickListener(new OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
      dLayout.closeDrawers();
      Bundle args = new Bundle();
      args.putString("Menu", menu[position]);
    }        
      });
 } 
}

所以请任何可以帮助我解决方案的人都会非常感激。

1 个答案:

答案 0 :(得分:1)

我认为您的onItemClick()方法应该定义为

@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
  dLayout.closeDrawers();
  Bundle args = new Bundle();
  args.putString("Menu", menu[position]);
  Intent i = new Intent(NavDrawer.this, SecondActivity.class);
  switch(position){
      case 0:
         i = new Intent(NavDrawer.this, Activity1.class);
         break;
      case 1:
         i = new Intent(NavDrawer.this, Activity2.class);
         break;
         ...
         ...
  }
  i.putExtra(args);
  startActivity(i);
}