笔记64 | 个人项目“易来”开发记录《二》处理Fragment

2018-01-16  本文已影响19人  项勇

需求描述

问题:

一个WebView放在Fragment中,我们都知道webView有一个goBack()方法,可以通过该方法对网页进行后退处理,由于Fragment本身并没有监听onBackPressed的方法,又处于一个Activity中,Activity除又对后退进行了3秒确定退出处理,所有导致

  1. Fragment中的WebView无法进行goBack();
需求:

需要在Fragment中监听到返回键,当WebView可以后退网页的时候,进行后退网页,当没有可后退的网页时(首页状态),点击返回调Activity中的onBackPressed方法;

处理方案

这位大神的方案
大神讲得通俗易懂,对我来说难度稍大,实现后再慢慢消化。。。
MianActivity:

public class Main extends FragmentActivity implements OnCheckedChangeListener,Framelayout3.BackHandLerInterface{

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
...
if (!(getActivity() instanceof BackHandLerInterface)) {
            throw new ClassCastException("Hosting activity must implement BackHandlerInterface");  
        }else{
            backHandLerInterface = (BackHandLerInterface) getActivity();
        }
}
...
@Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        backHandLerInterface.setSelectedFragment(this);
    }
...
private Framelayout3 framelayout3;
private long mTickForShow;
    @Override
    public void onBackPressed() {
        if (framelayout3 == null || !framelayout3.onBackPressed()) {
            backPress();
        }
    }
    
    public void backPress(){
        if (SystemClock.uptimeMillis()-mTickForShow<3000) {
            finish();
        }else{
            showToast(getString(R.string.gameover));
        }
        mTickForShow=SystemClock.uptimeMillis();
    }
...
    @Override
    public void setSelectedFragment(Framelayout3 backHandledFragment) {
        this.framelayout3 = backHandledFragment;
    }
}

Fragment:

public boolean onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
            return true;
        }else{
            return false;
        }
    }
...
protected BackHandLerInterface backHandLerInterface;

    public interface BackHandLerInterface{
        public void setSelectedFragment(Framelayout3 backHandledFragment);
    }
ezgif-3-44fb9ad33b.gif
上一篇下一篇

猜你喜欢

热点阅读