后退按钮强制关闭应用程序

时间:2013-09-10 03:56:29

标签: android webview back forceclose

我正在所有标签上使用webview创建标签式应用。每个标签都会转到另一个网址,然后用户可以点击链接,它会在应用中显示链接。但是,我在实现后退按钮时遇到问题,因此用户可以返回上一页。这是我的MainActivity.java:

package com.theprospectordaily;

import java.util.Locale;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.content.Intent;


public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {


    WebView myWebView;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the three primary sections of the app. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
CollectionPagerAdapter mCollectionPagerAdapter;

/**
 * The {@link android.support.v4.view.ViewPager} that will display the
 * object collection.
 */
ViewPager mViewPager;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);




// Create an adapter that when requested, will return a fragment
// representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must
// use
// getSupportFragmentManager.
mCollectionPagerAdapter = new CollectionPagerAdapter(
    getSupportFragmentManager());

// Set up action bar.
final ActionBar actionBar = getActionBar();


// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// Set up the ViewPager, attaching the adapter and setting up a listener
// for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
        // When swiping between different app sections, select
        // the corresponding tab.
        // We can also use ActionBar.Tab#select() to do this if
        // we have a reference to the
        // Tab.
        actionBar.setSelectedNavigationItem(position);
        }
    });

// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
    // Create a tab with text corresponding to the page title defined by
    // the adapter.
    // Also specify this Activity object, which implements the
    // TabListener interface, as the
    // listener for when this tab is selected.
    actionBar.addTab(actionBar.newTab()
        .setText(mCollectionPagerAdapter.getPageTitle(i))
        .setTabListener(this));
}
}

public void onTabUnselected(ActionBar.Tab tab,
    FragmentTransaction fragmentTransaction) {
}

public void onTabSelected(ActionBar.Tab tab,
    FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}

public void onTabReselected(ActionBar.Tab tab,
    FragmentTransaction fragmentTransaction) {
}


/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the primary sections of the app.
 */
public class CollectionPagerAdapter extends FragmentPagerAdapter {

final int NUM_ITEMS = 5; // number of tabs

public CollectionPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    Fragment fragment = new TabFragment();
    Bundle args = new Bundle();
    args.putInt(TabFragment.ARG_OBJECT, i);
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return NUM_ITEMS;
}

@Override
public CharSequence getPageTitle(int position) {
    String tabLabel = null;
    switch (position) {
    case 0:
    tabLabel = getString(R.string.label1);
    break;
    case 1:
    tabLabel = getString(R.string.label2);
    break;
    case 2:
    tabLabel = getString(R.string.label3);
    break;
    case 3:
    tabLabel = getString(R.string.label4);
    break;
    case 4:
    tabLabel = getString(R.string.label5);
    }

    return tabLabel;
}
}

/**
 * A fragment that launches other parts of the demo application.
 */
public static class TabFragment extends Fragment {

public static final String ARG_OBJECT = "object";

private WebView webView;
private Bundle webViewBundle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    webViewBundle = new Bundle();
}


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

    Bundle args = getArguments();
    int position = args.getInt(ARG_OBJECT);

    int tabLayout = 0;
    switch (position) {
    case 0:
    tabLayout = R.layout.tab1;
    break;
    case 1:
    tabLayout = R.layout.tab2;
    break;
    case 2:
    tabLayout = R.layout.tab3;
    break;
    case 3:
    tabLayout = R.layout.tab4;
    break;
    case 4:
        tabLayout = R.layout.tab5;
    break;
    }

    View rootView = inflater.inflate(tabLayout, container, false);

    webView = (WebView) rootView.findViewById(R.id.webView1);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/news/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();

    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView2);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());


    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/entertainment/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView3);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/sports/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView4);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/multimedia/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }

    webView = (WebView) rootView.findViewById(R.id.webView5);
    if (webView != null) {
    webView.setWebViewClient(new WebViewClient());

    if (webViewBundle == null || webViewBundle.isEmpty()) {
        webView.loadUrl("http://www.theprospectordaily.com/category/perspectives/");
    } else {
        webView.restoreState(webViewBundle);
        webViewBundle.clear();
    }
    }



    return rootView;
}
}

}

这是我第一次学习如何编码,所以我理解它到处都是,它可能有很多错误。我为此事先道歉!

4 个答案:

答案 0 :(得分:1)

您在哪里初始化myWebView?我不确定您要尝试做什么,但是从您的代码中我确定myWebView在您拨打myWebView.canGoBack()时为空时会抛出NullPointerException

答案 1 :(得分:0)

为什么要覆盖onKeyDown

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

你可以这样做它有它的具体方法

@Override
public void onBackPressed()
{       
        if (myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
    super.onBackPressed();      

}

注意:但我建议您为webview实现自己的后退按钮,以便用户可以使用后退按钮来存在活动

答案 2 :(得分:0)

尝试在您的活动中覆盖onBackPressed

@Override
public void onBackPressed() {
  if (mWebView.canGoBack()) {
    mWebView.goBack();
  } else {
    super.onBackPressed();
  }
}

答案 3 :(得分:0)

您需要做的是覆盖活动的onBackPressed功能。这将允许您在按下后退按钮时执行任何操作。

@Override
public void onBackPressed() {
    wv.goBack();

    //uncomment this if you want the back button to behave as normal
    //super.onBackPressed();
}