2013-12-17 67 views
0

我已經看過類似的問題,但是我還沒有找到解決我的問題的方法。onBack在使用片段時出現混亂

我有一個應用程序使用導航抽屜。我有一個MainActivity,各種片段佈局,各種FragmentActivities &。我的MainActivity代碼如下:

public class MainActivity extends Activity { 
private DrawerLayout mDrawerLayout; 
private ListView mDrawerList; 
private ActionBarDrawerToggle mDrawerToggle; 

// nav drawer title 
private CharSequence mDrawerTitle; 

// used to store app title 
private CharSequence mTitle; 

// slide menu items 
private String[] navMenuTitles; 
private TypedArray navMenuIcons; 

private ArrayList<NavDrawerItem> navDrawerItems; 
private NavDrawerListAdapter adapter; 

MediaPlayer ourSong; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
    ourSong = MediaPlayer.create(MainActivity.this, R.raw.audirs6); 

    SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
    boolean music = getPrefs.getBoolean("checkbox", true); 
    if (music == true) 
    ourSong.start(); 

    mTitle = mDrawerTitle = getTitle(); 

    // load slide menu items 
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); 

    // nav drawer icons from resources 
    navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons); 

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu); 

    navDrawerItems = new ArrayList<NavDrawerItem>(); 

    // adding nav drawer items to array 
    // AutoMart Home 
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1))); 
    // Search For A Car 
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1))); 

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1))); 

    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1))); 

    // Recycle the typed array 
    navMenuIcons.recycle(); 

    mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); 

    // setting the nav drawer list adapter 
    adapter = new NavDrawerListAdapter(getApplicationContext(), 
      navDrawerItems); 
    mDrawerList.setAdapter(adapter); 

    // enabling action bar app icon and behaving it as toggle button 
    getActionBar().setDisplayHomeAsUpEnabled(true); 
    getActionBar().setHomeButtonEnabled(true); 

    if (savedInstanceState == null) { 
     // on first time display view for first nav item 
     displayView(0); 
    } 

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 
      R.drawable.ic_drawer, //nav menu toggle icon 
      R.string.app_name, // nav drawer open - description for accessibility 
      R.string.app_name // nav drawer close - description for accessibility 
    ) { 
     public void onDrawerClosed(View view) { 
      getActionBar().setTitle(mTitle); 
      // calling onPrepareOptionsMenu() to show action bar icons 
      invalidateOptionsMenu(); 
     } 


     public void onDrawerOpened(View drawerView) { 
      getActionBar().setTitle(mDrawerTitle); 
      // calling onPrepareOptionsMenu() to hide action bar icons 
      invalidateOptionsMenu(); 
     } 
    }; 
    mDrawerLayout.setDrawerListener(mDrawerToggle); 

} 

/** 
* Slide menu item click listener 
* */ 
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); 
    } 
} 

@Override 
protected void onStop() { 
    // TODO Auto-generated method stub 
    super.onStop(); 
    ourSong.release(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // toggle nav drawer on selecting action bar app icon/title 
    if (mDrawerToggle.onOptionsItemSelected(item)) { 
     return true; 
    } 
    // Handle action bar actions click 
    switch (item.getItemId()) { 
    case R.id.action_settings: 
     Intent settings = new Intent("com.loui.automartdirectcars.SETTINGS"); 
     startActivity(settings); 
     break; 
    case R.id.aboutUs: 
     Intent about = new Intent("com.loui.automartdirectcars.ABOUT"); 
     startActivity(about); 
     break; 
    case (R.id.tellFriend): 
     Intent share = new Intent(Intent.ACTION_SEND); 
     share.setType("application/octet-stream"); 
     share.putExtra(Intent.EXTRA_SUBJECT, "AutoMart Direct Cars Android App"); 
     share.putExtra(Intent.EXTRA_TEXT, "Hey check out AutoMart Direct Cars Android App at https://play.google.com/store/apps/details?id=com.loui.automartdirectcars"); 
     startActivity(share); 
     break; 
    case R.id.contactDeveloper: 
     String body = "Enter your Question, Enquiry or Feedback below:\n\n"; 
     Intent contactDev = new Intent(Intent.ACTION_SEND); 
     contactDev.setType("application/octet-stream"); 
     contactDev.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); 
     contactDev.putExtra(Intent.EXTRA_SUBJECT, "AutoMart Direct Cars Android App"); 
     contactDev.putExtra(Intent.EXTRA_TEXT, body); 
     startActivity(contactDev); 
     break; 
    case R.id.exit: 
     finish(); 
     break; 
    } 
     return super.onOptionsItemSelected(item); 
} 

/* * 
* Called when invalidateOptionsMenu() is triggered 
*/ 
@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    // if nav drawer is opened, hide the action items 
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen); 
    menu.findItem(R.id.aboutUs).setVisible(!drawerOpen); 
    menu.findItem(R.id.tellFriend).setVisible(!drawerOpen); 
    menu.findItem(R.id.contactDeveloper).setVisible(!drawerOpen); 
    menu.findItem(R.id.exit).setVisible(!drawerOpen); 

    return super.onPrepareOptionsMenu(menu); 
} 

/** 
* Diplaying fragment view for selected nav drawer list item 
* @param <FragmentTransaction> 
* */ 
private <FragmentTransaction> void displayView(int position) { 
    // update the main content by replacing fragments 
    Fragment fragment = null; 
    switch (position) { 
    case 0: 
     fragment = new HomeFragment(); 
     break; 
    case 1: 
     fragment = new SearchCarFragment(); 
     break; 
    case 2: 
     fragment = new LogoFlipperFragment(); 
     break; 
    case 3: 
     fragment = new CommunityFragment(); 
     break; 
    default: 
     break; 
    } 


     FragmentManager fragmentManager = getFragmentManager(); 
     fragmentManager.beginTransaction() 
       .replace(R.id.frame_container, fragment).addToBackStack(null).commit(); 

     // update selected item and title, then close the drawer 
     mDrawerList.setItemChecked(position, true); 
     mDrawerList.setSelection(position); 
     setTitle(navMenuTitles[position]); 
     mDrawerLayout.closeDrawer(mDrawerList); 

} 



@Override 
public void setTitle(CharSequence title) { 
    mTitle = title; 
    getActionBar().setTitle(mTitle); 
} 

/** 
* When using the ActionBarDrawerToggle, you must call it during 
* onPostCreate() and onConfigurationChanged()... 
*/ 

@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); 
    // Pass any configuration change to the drawer toggls 
    mDrawerToggle.onConfigurationChanged(newConfig); 
    } 
public void onBackPressed() { 
    WebView mWebView = (WebView) findViewById(R.id.webView); 
    if (mWebView.canGoBack()) 
     mWebView.goBack(); 
    return; 
} 
} 

下面是網頁流量的活動:

public class HomeFragment extends Fragment { 

public HomeFragment(){} 


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

    View rootView = inflater.inflate(R.layout.fragment_home, container, false); 
    WebView mWebView = (WebView) rootView.findViewById(R.id.webView); 


    //Initializing and loading url in webview  
    mWebView = (WebView) rootView.findViewById(R.id.webView); 
    mWebView.getSettings().setJavaScriptEnabled(true); 
    mWebView.loadUrl("http://www.automartdirect.co.uk"); 
    mWebView.setWebViewClient(new WebViewClient() { 


     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      if(url.startsWith("http:") || url.startsWith("https:")) { 
       return false; 
      } 

      // Otherwise allow the OS to handle it 
      else if (url.startsWith("tel:")) { 
       Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url)); 
       startActivity(tel); 
       return true; 
      } 
      else if (url.startsWith("mailto:")) { 
       String body = "Enter your Question, Enquiry or Feedback below:\n\n"; 
       Intent mail = new Intent(Intent.ACTION_SEND); 
       mail.setType("application/octet-stream"); 
       mail.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); 
       mail.putExtra(Intent.EXTRA_SUBJECT, "Enquiry From AutoMart Direct Cars Android App"); 
       mail.putExtra(Intent.EXTRA_TEXT, body); 
       startActivity(mail); 
       return true; 
       } 
      return true; 
     } 
    }); 
    return rootView; 
    } 
} 

我有一個web視圖,並且這種膨脹的WebView佈局相對HomeFragment活性的片段佈局。我在MainActivity的底部放置了onBackPressed方法,以便能夠使用後退按鈕在此webview中返回。一切工作,因爲我想在webview內進行交互。所有在webview &中按下按鈕的鏈接都會根據需要將我帶回到以前的webview歷史記錄。當webview &中沒有更多的歷史記錄按鈕時,沒有任何反應,因爲我不希望應用程序退出,所以再次是理想的。然後這需要用戶點擊應用圖標以打開導航抽屜&選擇菜單中的另一項。

這裏是我卡住的地方。當我從導航抽屜中選擇另一個項目(片段)時,它會顯示,但是當我按下後退按鈕時,應用程序關閉並顯示消息'不幸的是,myapp已停止。我是否缺少一些代碼,或者是否必須爲每個片段添加onBackPressed代碼?更重要的是,我對onBackPressed方法的去向感到困惑。它應該只在MainActivity中進行,還是應該在每個FragmentActivity中進行?因爲它是唯一的onBackPressed方法,我在MainActivity中爲webview工作,但可能仍然是錯誤的做法。我需要什麼代碼來處理其他片段,當按下後退按鈕時,它不會關閉具有上述消息的應用程序,並且它應該放在哪裏?

任何幫助非常感謝!

這裏是logcat的:

12-17 22:34:03.957: D/AndroidRuntime(8477): Shutting down VM 
12-17 22:34:03.957: W/dalvikvm(8477): threadid=1: thread exiting with uncaught exception (group=0x41288930) 
12-17 22:34:03.987: E/AndroidRuntime(8477): FATAL EXCEPTION: main 
12-17 22:34:03.987: E/AndroidRuntime(8477): java.lang.NullPointerException 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at com.loui.automartdirectcars.MainActivity.onBackPressed(MainActivity.java:273) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.app.Activity.onKeyUp(Activity.java:2145) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.view.KeyEvent.dispatch(KeyEvent.java:2633) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.app.Activity.dispatchKeyEvent(Activity.java:2375) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1865) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3701) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3651) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2818) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.os.Handler.dispatchMessage(Handler.java:99) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.os.Looper.loop(Looper.java:137) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at android.app.ActivityThread.main(ActivityThread.java:5195) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at java.lang.reflect.Method.invokeNative(Native Method) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at java.lang.reflect.Method.invoke(Method.java:511) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 
12-17 22:34:03.987: E/AndroidRuntime(8477):  at dalvik.system.NativeStart.main(Native Method) 
+1

你有logcat顯示嗎?痕跡可能會指出這個問題。 –

+0

我認爲onBackPressed()應該在碎片內,因爲wbview的東西在碎片內。 – ImGeorge

+0

我已經添加了Logcat給任何能夠使其理解的人:-) – Loui

回答

2

顯然,這個問題基本上是在這些行:

WebView mWebView = (WebView) findViewById(R.id.webView); 
if (mWebView.canGoBack()) 

當你改變你的片段,你的視圖層次也改變和findViewById()返回null的方法。然後嘗試訪問空變量,導致NullPointerException。您可以修復,通過添加空校驗:if (mWebView != null && mWebView.canGoBack())

編輯

要回答你的第二個問題:你把你的onBackPressed事件處理邏輯,將取決於你想要達到什麼樣的地方。如果你想要一個活動中的所有片段的一般行爲,你應該把它放在你的活動中。但是如果你想要每個片段的特定行爲,你應該把邏輯放在每個片段中。 Here你可以找到一些處理方法。

+0

欣賞您的回覆。我只使用findViewById()只適用於onBackPressed的webview片段。但是我沒有其他片段的這種方法。我是否應該使用類似的方法或者引用其他片段來避免致命異常? – Loui

+0

對此,我認爲你可能有一個爲你的Fragments定義的接口,它擴展了實現你的行爲的一些基本的「onBackPressedListener」類,並且由於你保持對你的片段的引用,在確定你的webview爲null之後,召喚下面的片段,讓它背部按下 –

+0

這就意味着迭戈。我想每個片段的特定行爲,因此我需要處理每個片段中的邏輯。我多次看了一下這個鏈接,但是對我而言,我可能應該在碎片中放置類似的事件處理程序,而不是在MainActivity中,因爲每個碎片都有不同的行爲。在我精神崩潰之前,將繼續使用它2moro :-)。今天我已經吃夠了。非常感謝您的回覆! – Loui