2014-11-01 185 views
0

如果我點擊導航抽屜項目中的圖庫,我需要爲圖庫頁面創建一個單獨的活動。下面我張貼了我到目前爲止嘗試過的代碼。導航抽屜項目

MainActivity.java:

private class SlideMenuClickListener implements 
      ListView.OnItemClickListener { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, 
       long id) { 
      // display view for selected nav drawer item 
      displayView(position); 
     } 
    } 


private void displayView(int position) { 
    // update the main content by replacing fragments 
    Fragment fragment = null; 
    switch (position) { 
    case 0: 
     fragment = new GalleryFragment(); 
     break; 
    case 1: 
     fragment = new FindPeopleFragment(); 
     break; 
    case 2: 
     fragment = new PhotosFragment(); 
     break; 

    default: 
     break; 
    } 

GalleryFragment.java:

public class GalleryFragment extends Fragment { 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.chapter, container, false); 

    Intent i = new Intent(getActivity(), GalleryActivity.class); 
    startActivity(i); 

    return rootView; 
} 

}

gallery.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

</LinearLayout> 

GalleryActivity.java:

public class GalleryActivity extends Activity { 

    TextView textView1; 

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

     textView1=(TextView)findViewById(R.id.textView1); 


    } 

} 

gallery_activity.xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Lesson Page" /> 

</LinearLayout> 

到目前爲止,我不喜歡它this.But它不是working.In輸出,首先我正在爲圖庫獲取單獨的活動。那麼如果我點擊後退按鈕,它會顯示主頁。但是,如果我點擊導航抽屜中的圖庫,它不會移動到單獨的圖庫活動。logcat中沒有錯誤。

+0

什麼時候「不工作」會怎樣? – Henry 2014-11-01 06:44:43

+0

@亨利沒有日誌錯誤。但它不起作用意味着它不會移動到單獨的活動。 – Steve 2014-11-01 06:46:02

回答

0

displayView中的代碼確實沒有任何效果(假設您沒有發佈任何內容)。它設置一個局部變量fragment,該方法結束時超出範圍。

如果你想開始GalleryActivity你需要類似下面的代碼:

Intent i = new Intent(context, GalleryActivity.class); 
startActivity(i); 
+0

現在我在這一行得到空指針異常'Intent i = new Intent(context,GalleryActivity.class);' – Steve 2014-11-01 07:00:18

+0

我寫了* similar *。這些文字並不意味着被逐字複製。您需要將'context'參數設置爲有效的上下文。 – Henry 2014-11-01 07:06:33

+0

我這樣做.'private靜態上下文mContext;'然後'意圖我=新的意圖(mContext,GalleryActivity.class);' – Steve 2014-11-01 07:07:59