在后退按钮按下webview片段是电影回到以前的片段而不是以前的网页

时间:2017-10-13 03:22:27

标签: android android-fragments webview

我是android开发的初学者,实际上我有一个带webview的片段。我的问题是,当我处于片段并单击后退按钮时,它不会返回到上一个网页,而是返回到上一个片段。所以请帮我解决这个问题。

这是我的主要活动代码:

public class MainActivity extends AbsRuntimePermission implements NavigationView.OnNavigationItemSelectedListener {
    //, GoogleApiClient.OnConnectionFailedListener {

    private static final int REQUEST_PERMISSION = 10;
    private Toolbar toolBar;
    private NavigationView navDrawer;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private FirebaseAuth.AuthStateListener authListener;
    private FirebaseAuth auth;
    private View btnLogOut;
    private int selectedItem;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference myRef;
    //  private GoogleApiClient googleApiClient;
    private FloatingActionButton fab;
    private CoordinatorLayout coordinatorLayout;
    private HomeFragment homeFragment=new HomeFragment();

    final String TAG = this.getClass().getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        auth = FirebaseAuth.getInstance();
        final FirebaseUser user = auth.getCurrentUser();
        String userID = user.getUid();
        // Check if no view has focus:
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, Contact_FAB.class);
                startActivity(intent);
            }
        });
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.main_content, homeFragment);
        tx.commit();
        final WebView webView = (WebView) findViewById(R.id.WV);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            public void onPageFinished(WebView view, String url) {
                // do your stuff here}
                @Override
                public void onReceivedError (WebView view,int errorCode, String description, String
                failingUrl){
                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });

    webView.loadUrl("https://google.co.in");

            requestAppPermissions(new String[] {
                Manifest.permission.READ_CONTACTS,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
            },
            R.string.msg,REQUEST_PERMISSION);

            toolBar =(Toolbar)

            findViewById(R.id.app_bar);

            setSupportActionBar(toolBar);

            // If a notification message is tapped, any data accompanying the notification
            // message is available in the intent extras. In this project the launcher
            // intent is fired when the notification is tapped, so any accompanying data would
            // be handled here. If you want a different intent fired, set the click_action
            // field of the notification message to the desired intent. The launcher intent
            // is used when no click_action is specified.
            //
            // Handle possible data accompanying notification message.
    if(

            getIntent().

            getExtras() !=null)

            {
                for (String key : getIntent().getExtras().keySet()) {
                    String value = getIntent().getExtras().getString(key);
                    if (key.equals("AnotherActivity") && value.equals("True")) {
                        Intent intent = new Intent(this, AnotherActivity.class);
                        intent.putExtra("value", value);
                        startActivity(intent);
                        finish();
                    }

                }
            }

            // subscribeToPushService();

            drawerLayout =(DrawerLayout)

            findViewById(R.id.drawer_layout);

            navDrawer =(NavigationView)

            findViewById(R.id.menu_drawer);
    navDrawer.setNavigationItemSelectedListener(this);
            drawerToggle =new

            ActionBarDrawerToggle(this,drawerLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
    drawerLayout.setDrawerListener(drawerToggle);
    drawerToggle.syncState();
            selectedItem =savedInstanceState ==null?R.id.nav_item_1 :savedInstanceState.getInt("selectedItem");

        }


        @Override
        public boolean onNavigationItemSelected (MenuItem menuItem){
            menuItem.setChecked(true);
            selectedItem = menuItem.getItemId();
            Fragment fragment = null;
            switch (selectedItem) {
                case R.id.nav_item_1:
                    fragment = new HomeFragment();
                    break;
                case R.id.nav_item_2:
                    fragment = new MicrosoftDskFragment();
                    break;
                case R.id.nav_item_3:
                    fragment = new GoogleDskFragment();
                    break;
                case R.id.nav_item_4:
                    fragment = new AppleDskFragment();
                    break;
                case R.id.nav_item_5:
                    fragment = new OthersDskFragment();
                    break;
                case R.id.nav_item_6:
                    fragment = new MobiSpecsFragment();
                    break;
                case R.id.nav_item_8:
                    Intent intent = new Intent(MainActivity.this, About.class);
                    startActivity(intent);
                    break;
                default:
                    break;
            }

            if (!DetectConnection.checkInternetConnection(MainActivity.this)) {
                Toast.makeText(MainActivity.this, "Plz check your network connectivity", Toast.LENGTH_SHORT).show();
            } else {

                if (fragment != null) {

                    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.main_content, fragment);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                }
            }

            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        }

        boolean twice = false;

        @Override
        public void onBackPressed () {
            DrawerLayout layout = (DrawerLayout) findViewById(R.id.drawer_layout);

            if (layout.isDrawerOpen(GravityCompat.START)) {
                layout.closeDrawer(GravityCompat.START);
            } else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                    getSupportFragmentManager().popBackStack();
                } else {
                    Log.d(TAG, "click");

                    if (twice == true) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                        System.exit(0);
                    }
                    twice = true;
                    Log.d(TAG, "twice: " + twice);

                    //super.onBackPressed();
                    Toast.makeText(MainActivity.this, "Please Press Again To Exit", Toast.LENGTH_SHORT).show();

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            twice = false;
                            Log.d(TAG, "twice: " + twice);
                        }
                    }, 3000);

                }
            }
        }

        @Override
        public boolean onKeyDown ( int keyCode, KeyEvent event){
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        homeFragment.OnKeyDown(keyCode);
                        return true;
                }
            }
            return super.onKeyDown(keyCode, event);
        }


        @Override
        public boolean onCreateOptionsMenu (Menu menu){
            // Inflate the menu; this adds items to the action bar if it is present.

            getMenuInflater().inflate(R.menu.menu_main, menu);

            return super.onCreateOptionsMenu(menu);
        }

        @Override
        public boolean onOptionsItemSelected (MenuItem item){
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();


            //noinspection SimplifiableIfStatement
            if (id == R.id.profile) {
                Intent intent = new Intent(MainActivity.this, Profile.class);
                startActivity(intent);
                return true;
            }


            return super.onOptionsItemSelected(item);
        }


        @Override
        public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState){
            super.onSaveInstanceState(outState, outPersistentState);

            outState.putInt("selectedItem", selectedItem);
        }

        @Override
        public void onPermissionsGranted ( int requestCode){
            //Do anything when permisson granted
            //   Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_LONG).show();
        }


/*    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

*/

    }
}

这是我的家庭片段代码:

@SuppressWarnings("ALL")

public class HomeFragment扩展了Fragment {

WebView webView;
SwipeRefreshLayout swipeView;

public HomeFragment() {
    // Required empty public constructor
}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.container);
    webView = (WebView) rootView.findViewById(R.id.webView);


    webView.getSettings().setJavaScriptEnabled(true);
    // Inflate the layout for this fragment
    webView.loadUrl("https://google.co.in");

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webView.stopLoading();
            webView.clearView();
            Intent intent = new Intent(getActivity(), ErrorActivity.class);
            startActivity(intent);
            swipeView.setEnabled(false);
            super.onReceivedError(view, errorCode, description, failingUrl);

        }

        public void onPageFinished(WebView view, String url) {
            // do your stuff here
            swipeView.setRefreshing(false);

        }

    });


    swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            swipeView.setRefreshing(true);

            (new Handler()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:window.location.reload( true )");

                }
            }, 2000);
        }
    });
    return rootView;
}
    @Override
    public void onAttach (Activity activity){
        super.onAttach(activity);
    }

    @Override
    public void onDetach () {
        super.onDetach();
    }

  public void OnKeyDown(int keyCode) {
    if (webView != null) {
        if (webView.canGoBack()) {
            webView.goBack();

        } else {
            getActivity().onBackPressed();
        }
    }
}
}

2 个答案:

答案 0 :(得分:0)

在FragmentManager替换Fragment的onNavigationItemSelected中,不要将其添加到backstack中:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.main_content, fragment);
                    fragmentTransaction.commit();

如果将其添加到Backstack,这意味着您将Fragment添加到Activity的历史堆栈中,当您按下后退按钮时,该操作将被还原。所以每次添加一个新的Fragment时,堆栈都是这样的:[fragment1] [fragment2] [fragment3],如果按下后退按钮,它将删除最后添加的动作,因此删除[fragment3]将显示你是[fragment2]。

希望这有帮助。

答案 1 :(得分:0)

在片段中创建一个方法,例如在按下键时执行操作

public void OnKeyDown(int keyCode){
   if (mWebView.canGoBack()) {
       mWebView.goBack();
   } else {
       getActivity().onBackPressed();
   }
}

并在相应的活动中覆盖keyDown方法并按键处理

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                yourFagmentObject.OnKeyDown(keyCode);
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

从webViewFragment中删除webView.setOnKeyListener(新的View.OnKeyListener()。