如何在android的片段webview中处理onback

时间:2015-08-19 07:34:58

标签: java android android-fragments android-webview

在我的片段活动中使用webview。当我点击webview上的超链接时,它会重定向到指定的网址。但问题是当我点击后面时它被重定向到主片段而不是previos页面。任何人都可以帮我如何重定向到webview上的上一页.Below是我在mainactivity中的代码,我处理片段onback按事件。

private void selectItem(int position) {

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Locate Position
    Fragment fragment = null;
    switch (position) {
    case 0:
        //ft.replace(R.id.content_frame, frag,"home");
        fragment=new Fagmentmain();
        /*startActivity(new Intent(MainActivity.this,Category.class));*/
        break;
    case 1:
        //ft.replace(R.id.content_frame, webfrag,"web");
        fragment=new WebFragment();
        /*Intent intent=new Intent(MainActivity.this,News.class);
        intent.putExtra("pos",0);
        startActivity(intent);*/
        //startActivity(new Intent(MainActivity.this,News.class));
        break;
    case 2:
        //ft.replace(R.id.content_frame, aboutfrag,"about");
        Intent intent1=new Intent(MainActivity.this,News.class);
        intent1.putExtra("pos",1);
        startActivity(intent1);
        break;
    case 3:
        Intent intent2=new Intent(MainActivity.this,News.class);
        intent2.putExtra("pos",2);
        startActivity(intent2);
        break;
    }
    /*ft.commit();
    mDrawerList.setItemChecked(position, true);
    setTitle(title[position]);
    mDrawerLayout.closeDrawer(mDrawerList);*/


    if(fragment != null){
        FragmentManager fragmanager=getSupportFragmentManager();
        fragmanager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("").commit();

        mDrawerList.setItemChecked(position, true);
        setTitle(title[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }
}


@Override
public void onBackPressed() {

    super.onBackPressed();

    FragmentManager fm = getSupportFragmentManager();
    //FragmentTab1 frag=(FragmentTab1)getSupportFragmentManager().findFragmentById(arg0)

    if (fm.getBackStackEntryCount() > 0) {


        Log.e("back stack entry", fm.getBackStackEntryCount() + "");
        fm.popBackStack();

    }

}

1 个答案:

答案 0 :(得分:0)

通过在我的片段

中添加以下代码解决了这个问题

webview.setOnKeyListener(new OnKeyListener(){

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub

            if((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack() ){
                webview.goBack();
                return true;
            }
            return false;
        }
    });