2015-04-08 53 views
1

因此,我需要爲我的主要活動添加導航抽屜,爲此我使用本教程http://www.recursiverobot.com/post/59404388046/implementing-the-new-navigation-drawer-in-android。我修改了xmls並將代碼添加到了我的主要活動中。教程代碼獨立正常工作,但是當我將其與主要活動集成時,它會提供以下logcat消息。Android:添加導航抽屜會產生運行時錯誤

這是我的代碼

public class MainActivity extends ListActivity { 

    private String[] mPlanetTitles; 
    private DrawerLayout mDrawerLayout; 
    private ListView mDrawerList; 
    private CharSequence mTitle; 
    private ActionBarDrawerToggle mDrawerToggle; 

    private PackageManager packageManager = null; 
    private List<ApplicationInfo> applist = null; 
    private AppAdapter listadapter = null; 

    public boolean[] status = { true, false, false, false, false, false, false, false, false, false }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     mTitle = "test"; 

     mPlanetTitles = new String[]{"one", "two", "three"}; 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerList = (ListView) findViewById(R.id.left_drawer); 

     // Set the adapter for the list view 
     mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles)); 
     // Set the list's click listener 
     mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); 

     mDrawerToggle = new ActionBarDrawerToggle(
       this,     /* host Activity */ 
       mDrawerLayout,   /* DrawerLayout object */ 
       R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ 
       R.string.drawer_open, /* "open drawer" description */ 
       R.string.drawer_close /* "close drawer" description */ 
     ) { 
      /** Called when a drawer has settled in a completely closed state. */ 
      public void onDrawerClosed(View view) { 
       getActionBar().setTitle(mTitle); 
      } 

      /** Called when a drawer has settled in a completely open state. */ 
      public void onDrawerOpened(View drawerView) { 
       getActionBar().setTitle(mTitle); 
      } 
     }; 

     // Set the drawer toggle as the DrawerListener 
     mDrawerLayout.setDrawerListener(mDrawerToggle); 

     ActionBarActivity obj = new ActionBarActivity(); 

     obj.getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     obj.getSupportActionBar().setHomeButtonEnabled(true); 

     if(savedInstanceState!=null){ 
      status = savedInstanceState.getBooleanArray("status"); 
     } 

     OnItemClickListener itemClickListener = new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> lv, View item, int position, long id) { 

       ListView lView = (ListView) lv; 
       SimpleAdapter adapter = (SimpleAdapter) lView.getAdapter(); 
       HashMap<String,Object> hm = (HashMap) adapter.getItem(position); 
       /** The clicked Item in the ListView */ 
       RelativeLayout rLayout = (RelativeLayout) item; 
       /** Getting the toggle button corresponding to the clicked item */ 
       ToggleButton tgl = (ToggleButton) rLayout.getChildAt(1); 

       String strStatus = ""; 
       if(tgl.isChecked()){ 
        tgl.setChecked(false); 
        strStatus = "Off"; 
        status[position]=false; 
       }else{ 
        tgl.setChecked(true); 
        strStatus = "On"; 
        status[position]=true; 
       } 
       Toast.makeText(getBaseContext(), (String) hm.get("txt") + " : " + strStatus, Toast.LENGTH_SHORT).show(); 
      } 
     }; 
     packageManager = getPackageManager(); 
     new LoadApplications().execute(); 
    } 

    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 
     outState.putBooleanArray("status", status); 
    } 

    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) { 
     super.onListItemClick(l, v, position, id); 
     ApplicationInfo app = applist.get(position); 

     try{ 
      Intent intent = packageManager.getLaunchIntentForPackage(app.packageName); 

      if(intent != null) { 
       startActivity(intent); 
      } 
     } catch(ActivityNotFoundException e) { 
      Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); 
     } catch(Exception e) { 
      Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); 
     } 
    } 

    private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) { 

     ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>(); 

     for(ApplicationInfo info : list) { 
      try{ 
       if(packageManager.getLaunchIntentForPackage(info.packageName) != null) { 
        appList.add(info); 
       } 
      } catch(Exception e) { 
       e.printStackTrace(); 
      } 
     } 

     return appList; 
    } 

    private class LoadApplications extends AsyncTask<Void, Void, Void> { 

     private ProgressDialog progress = null; 

     @Override 
     protected Void doInBackground(Void... params) { 

      applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA)); 

      listadapter = new AppAdapter(MainActivity.this, R.layout.list_item, applist); 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      setListAdapter(listadapter); 
      progress.dismiss(); 
      super.onPostExecute(result); 
     } 

     @Override 
     protected void onPreExecute() { 
      progress = ProgressDialog.show(MainActivity.this, null, "Loading apps info..."); 
      super.onPreExecute(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    protected void onPostCreate(Bundle savedInstanceState) { 
     super.onPostCreate(savedInstanceState); 
     // Sync the toggle state after onRestoreInstanceState has occurred. 
     mDrawerToggle.syncState(); 
    } 

    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     mDrawerToggle.onConfigurationChanged(newConfig); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Pass the event to ActionBarDrawerToggle, if it returns 
     // true, then it has handled the app icon touch event 
     if (mDrawerToggle.onOptionsItemSelected(item)) { 
      return true; 
     } 
     // Handle your other action bar items... 
     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * Swaps fragments in the main content view 
    */ 
    private void selectItem(int position) { 
     Toast.makeText(this, R.string.app_name, Toast.LENGTH_SHORT).show(); 
     // Highlight the selected item, update the title, and close the drawer 
     mDrawerList.setItemChecked(position, true); 
     setTitle(mPlanetTitles[position]); 
     mDrawerLayout.closeDrawer(mDrawerList); 
    } 

    @Override 
    public void setTitle(CharSequence title) { 
     mTitle = title; 
     ActionBarActivity obj = new ActionBarActivity(); 
     obj.getSupportActionBar().setTitle(mTitle); 
    } 

    private class DrawerItemClickListener implements ListView.OnItemClickListener { 
     @Override 
     public void onItemClick(AdapterView parent, View view, int position, long id) { 
      selectItem(position); 
     } 
    } 
} 

這是清單文件。

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.listofapps" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="11" 
     android:targetSdkVersion="21" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/Theme.Example" > 
     <activity 
      android:name=".MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

這是主要活動。

<android.support.v4.widget.DrawerLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:id="@+id/drawer_layout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     tools:context=".MainActivity"> 
    <!-- The main content view --> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" > 
     <ListView 
      android:id="@android:id/list" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 
     </ListView> 
    </LinearLayout> 
     <ListView 
      android:id="@+id/left_drawer" 
      android:layout_width="240dp" 
      android:layout_height="match_parent" 
      android:layout_gravity="start" 
      android:choiceMode="singleChoice" 
      android:divider="@android:color/transparent" 
      android:dividerHeight="0dp" 
      android:background="#111"/> 
</android.support.v4.widget.DrawerLayout> 

enter image description here

可有人請給我一個提示或引導我。提前致謝 !!

+0

@SilentKnight完成! – varunkr

+0

你能找到哪條線投擲NPE?你的logcat跟蹤不完整,我想 – SilentKnight

+0

這是什麼ActionBarActivity obj = new ActionBarActivity();?你不能使用這樣的東西。並通過複製文本而不是圖像來發布完整的logcat。 – Harry

回答

1

我得到了解決被發現。我實際上是Android新手,並且正在使用對象來訪問其他類的功能。我創建對象obj並在以後使用它的行實際上是Harry指出的錯誤。一旦我刪除了,我只需要更改getSupportActionBar getActionBar,我完成了。謝謝您的幫助 !!

0

在您的AndroidManifest.xml中部署MainActivity。 像這樣:

<activity 
    android:name=".MainActivity" 
    ... 
    > 
</activity> 

你logcat的跟蹤意味着Activity不能通過AndroidManifest.xml

+0

非常感謝您的回覆,但我無法完全理解您的意思。我想我已經按照你的要求做了。 – varunkr

+0

只要你解決了你的問題。 – SilentKnight

+0

@SilentKinght不,我沒有:( – varunkr