Lê Khánh Vinh
Lê Khánh Vinh

Reputation: 2611

webview fragment press back to return to

Hi I have an android app which a recycleview. When user click a button on a recycle viewholder. app will launch a webview (inside fragment). I want to handle when user click back button, webview will goback if there is a history, and if there is no history, the app will close the webview fragment and come back the recycleview.

I have successfull handle the back when there is a history (but webview can not come back to recycle view if there is no history

Here is my webview code

webView.setOnKeyListener(new View.OnKeyListener() {

                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        if (webView.canGoBack()) {
                            webView.goBack();
                        }else {
                            getActivity().getSupportFragmentManager().popBackStack();
                        }
                        return true;
                    }
                    return false;
                }

            });

Anything wrong with these code? any help is much appreciate. Thanks

Edit i use these code inside recycleview adapter class to handle button click on ViewHolder class

url.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Bundle bundle = new Bundle();
                    bundle.putString("topStoryUrl", topStories.get(getLayoutPosition()).getUrl());

                    TopStoryWebView topStoryWebViewFragment = new TopStoryWebView();
                    topStoryWebViewFragment.setArguments(bundle);
                    if (ItemListActivity.mTwoPane) {

                        ((FragmentActivity) context).getSupportFragmentManager()
                                .beginTransaction()
                                .add(R.id.item_detail_container, topStoryWebViewFragment)
                                .commit();
                    } else {
                        topStoryWebViewFragment.setArguments(bundle);
                        ((FragmentActivity) context).getSupportFragmentManager()
                                .beginTransaction()
                                .add(R.id.frameLayout, topStoryWebViewFragment)
                                .commit();
                    }
                }
            });

Upvotes: 0

Views: 369

Answers (1)

Mohd Asif Ahmed
Mohd Asif Ahmed

Reputation: 2170

addToBackStack will add your fragment to stack, and you can access this stack later

((FragmentActivity) context).getSupportFragmentManager()
.beginTransaction()
.add(R.id.item_detail_container, topStoryWebViewFragment) 
// Add this transaction to the back stack (name is an optional name for this back stack state, or null). 
.addToBackStack(null) 
.commit();

Upvotes: 1

Related Questions