带有Webview的片段利用harware后退按钮转到上一个网页 [英] Fragment with Webview utilize harware back button to go to previous webpage

查看:71
本文介绍了带有Webview的片段利用harware后退按钮转到上一个网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎在堆栈溢出问题上被问了很多,但是随着SDK的更改,答案似乎不再可行(我可能是错的!).

This appears to have been asked a lot on stack overflow, but with answers which appear to no longer be implementable with changes to the SDK (I may be wrong!).

我一直在尝试允许MainActivity中的一个片段使用硬件按钮返回到片段中Web视图中的上一页.

I have been trying to allow a fragment inside my MainActivity to use the hardware button to go back to the previous page inside a webview in the fragment.

我已经尝试使用return super.onKeyDown(keyCode,event);作为功​​能的一部分,但onKeyDown在我的项目中显示为无效.

I have tried using return super.onKeyDown(keyCode, event); as part of a function but onKeyDown does not come up as valid in my project.

这是我的BlogFragment,其中包含网络视图:

This is my BlogFragment containing the webview:

public class BlogFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

WebView wv;
private OnFragmentInteractionListener mListener;

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment blog.
 */
// TODO: Rename and change types and number of parameters
public static BlogFragment newInstance(String param1, String param2) {
    BlogFragment fragment = new BlogFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;

}

public static boolean canGoBack(){
    return wv.canGoBack();
}

public static void goBack(){
    wv.goBack();
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


    View view=inflater.inflate(R.layout.fragment_blog, null);

    wv = (WebView) view.findViewById(R.id.webview);
    WebSettings settings = wv.getSettings();
    wv.setWebChromeClient(new WebChromeClient() {
    });
    final String mimeType = "text/html";
    final String encoding = "UTF-8";
    String html = getHTML();
    settings.setJavaScriptEnabled(true);
    wv.loadDataWithBaseURL("http://www.bbc.co.uk", html, mimeType, encoding, "");

    return view;

}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}


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

public String getHTML() {
    String html = "<iframe width=\"100%\" height=\"100%\" src=\"http://blog.mrgyro.co.uk\" frameborder=\"0\" allowfullscreen></iframe>";
    return html;
}


/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

}

活动:

public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks, BlogFragment.OnFragmentInteractionListener, HomeFragment.OnFragmentInteractionListener {


/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));

}

@Override
public void onBackPressed() {
    if(BlogFragment.canGoBack()){
        BlogFragment.goBack();
    }else{
        super.onBackPressed();
    }

}

@Override
public void onNavigationDrawerItemSelected(int position) {
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();

    switch (position) {
        case 0:
            HomeFragment homeFragment = new HomeFragment();
            transaction.replace(R.id.container, homeFragment);
            break;
        case 1:
            BlogFragment blogFragment = new BlogFragment();
            transaction.replace(R.id.container, blogFragment);
            break;

    }
    transaction.commit();
}

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            break;
        case 4:
            mTitle = getString(R.string.title_section4);
            break;
    }
}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    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.action_settings) {
   //     return true;
   // }

    return super.onOptionsItemSelected(item);
}

@Override
public void onFragmentInteraction(Uri uri) {

}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = null;
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
            case 1:
                rootView = inflater.inflate(R.layout.fragment_home, container, false);
                break;
            case 2:
                rootView = inflater.inflate(R.layout.fragment_blog, container, false);
                break;
            case 3:
               // rootView = inflater.inflate(R.layout.fragment_test, container, false);
                break;
            case 4:
                //rootView = inflater.inflate(R.layout.fragment_info, container, false);
                break;
            default:
                Log.e("TAG", "Unrecognized section: " + getArguments().getInt(ARG_SECTION_NUMBER));

        }
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}




}

谢谢.

我已经用最近的尝试更新了博客片段,但是当尝试静态wv.canGoBack()和wv.goBack()都返回错误非静态字段'wv'不能从静态上下文

I have updated the blog fragment with my most recent attempt, however when trying to static wv.canGoBack() and wv.goBack() both return the error "Non-Static field 'wv' cannot be referenced from a static context

推荐答案

尝试覆盖 onBackPressed()在您的 Activity 中,并使其戳 WebView .

Try overriding onBackPressed() in your Activity and make it poke the WebView.

顺便说一句-您也可以发布包含 onKeyDown 方法的 Activity 片段.

BTW - you could post the piece of Activity containing the onKeyDown method as well.

首先实例化片段:

BlogFragment blogFragment = new BlogFragment();
blogFragment.canGoBack();

,然后从您的方法中删除 static .:)

and then just remove the static from your methods. :)

OP的实现(感谢Klotor)在MainActivity工具的顶部:

OPs implementation (with thanks to Klotor) At the head of MainActivity implement:

BlogFragment blogFragment = new BlogFragment();

然后执行:

public void onBackPressed() {

    blogFragment.canGoBack();
    if(blogFragment.canGoBack()){
        blogFragment.goBack();
    }else{
        super.onBackPressed();
    }

}

为了避免在使用片段之间导航的方法时崩溃,片段是在onBackPressed外部实例化的.在这种情况下,您需要实例化该片段的新实例,而不是实例化整个新片段.

The fragment is instantiated outside of the onBackPressed in order to prevent crashing when using a method to navigate between fragments. In this case you need to instantiate a newinstance of the fragment, rather than a whole new fragment.

这篇关于带有Webview的片段利用harware后退按钮转到上一个网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆