Fragment内放置WebView,监听返回键,并返回之前打开的网页

package com.mt.kj;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.widget.Toast;

import com.mt.kj.databinding.ActivityNewMainBinding;
import com.mt.kj.ui.webview.WebViewFragment;
import com.mt.kj.utlis.MyLogger;
import com.tencent.smtt.sdk.WebView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lenovo on 2018/1/13.
 */

public class NewMianActivity extends FragmentActivity implements TabLayout.OnTabSelectedListener {
    private ArrayList mFragmentArrayList;
    private ArrayList mStringList;
    private ActivityNewMainBinding mBinding;
      private String url = "https://wapbaike.baidu.com/item/孙俪";
      private String url01 = "https://wapbaike.baidu.com/item/张嘉译";
      private String url02 = "https://wapbaike.baidu.com/item/科比";
    private String url03 = "https://wapbaike.baidu.com/item/%E7%AB%A0%E5%AD%90%E6%80%A1";
    private String url04 = "https://wapbaike.baidu.com/item/迪丽热巴";
    private WebViewFragment mWebViewFragment;
    private WebViewFragment mWebViewFragment1;
    private WebViewFragment mWebViewFragment2;
    private WebViewFragment mWebViewFragment3;
    private WebViewFragment mWebViewFragment4;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_new_main);
        initView();
    }


    private void initView() {
        mFragmentArrayList = new ArrayList<>();
        mStringList = new ArrayList<>();
        mStringList.add("孙俪");
        mStringList.add("张嘉译");
        mStringList.add("科比");
        mStringList.add("章子怡");
        mStringList.add("迪丽热巴");
        mWebViewFragment = WebViewFragment.newInstance(url);
        mWebViewFragment1 = WebViewFragment.newInstance(url01);
        mWebViewFragment2 = WebViewFragment.newInstance(url02);
        mWebViewFragment3 = WebViewFragment.newInstance(url03);
        mWebViewFragment4 = WebViewFragment.newInstance(url04);
        mFragmentArrayList.add(mWebViewFragment);
        mFragmentArrayList.add(mWebViewFragment1);
        mFragmentArrayList.add(mWebViewFragment2);
        mFragmentArrayList.add(mWebViewFragment3);
        mFragmentArrayList.add(mWebViewFragment4);
        showViewPager(mBinding.mTabLayout, mBinding.vpViewpager, mStringList, mFragmentArrayList, 3, false);
        mBinding.mTabLayout.addOnTabSelectedListener(this);
    }


    /**
     * 设置 viewpage +fragment
     *
     * @param tabLayout
     * @param viewPager
     * @param mStringList        标题
     * @param mFragmentArrayList fragment
     * @param num                设置预加载数
     * @param isMode             设置是否横向滑动
     * @return
     */
    public GroupFragmentPagerAdapterUtil showViewPager(TabLayout tabLayout
            , ViewPager viewPager
            , List mStringList, List mFragmentArrayList
            , int num, boolean isMode) {
        for (int i = 0; i < mStringList.size(); i++) {
            tabLayout.addTab(tabLayout.newTab().setText(mStringList.get(i)));
        }
        GroupFragmentPagerAdapterUtil adapterUtil =
                new GroupFragmentPagerAdapterUtil(getSupportFragmentManager(), mFragmentArrayList, mStringList);
        viewPager.setOffscreenPageLimit(num); //设置预加载个数
        viewPager.setAdapter(adapterUtil);
        viewPager.setCurrentItem(0);//设置当前加载页面
        tabLayout.setupWithViewPager(viewPager);
        if (isMode)//设置可以滑动
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        return adapterUtil;
    }

    /**
     * 判断 当前那个fragment 获取当前的webview 先返回webview 上一页 ,如果到头了在退出程序
     */
    private long mExitTime;
    public static final int TOAST_SHOW_EXIT = 1000;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mPosition == 0) {
                haswebviw((WebView) mWebViewFragment.getView().findViewById(R.id.webView));
            } else if (mPosition == 1) {
                haswebviw((WebView) mWebViewFragment1.getView().findViewById(R.id.webView));
            } else if (mPosition == 2) {
                haswebviw((WebView) mWebViewFragment2.getView().findViewById(R.id.webView));
            } else if (mPosition == 3) {
                haswebviw((WebView) mWebViewFragment3.getView().findViewById(R.id.webView));
            } else if (mPosition == 4) {
                MyLogger.e("tag",mWebViewFragment4.getView()+"===");
                haswebviw((WebView) mWebViewFragment4.getView().findViewById(R.id.webView));
            } else {
                exitBy2Click();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void haswebviw(WebView webView) {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            exitBy2Click();   //这是退出方法
        }
    }

    private void exitBy2Click() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(this, "再点击返回一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

private  int mPosition;
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        mPosition= tab.getPosition();
        MyLogger.e("tag","01=="+mPosition+"");
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        MyLogger.e("tag","02=="+tab.getPosition()+"");
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        MyLogger.e("tag","03=="+tab.getPosition()+"");
    }
}


// 方法二:简单实用  推荐使用方法二,简单快捷方便
   mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK ) {
                        //这里处理返回键事件
                        if (mWebView.canGoBack()){
                            mWebView.goBack();
                            //Toast.makeText(getActivity(), "ok", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                    }
                }
                return false;
            }
        });


你可能感兴趣的:(Fragment内放置WebView,监听返回键,并返回之前打开的网页)