从菜单片段onClick调用MainActivity中的WebView

时间:2014-09-05 22:04:31

标签: android android-fragments webview

我有一个oncreate的活动,我之前刚刚调用一个void函数来加载webview中的url

private CharSequence mTitle;
private String mPageURL;

private WebView mWebView;

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

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

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

    mPageURL = "http://beta.html5test.com/";
    loadWebViewContent();
}

public void loadWebViewContent() {
    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    mWebView.setWebViewClient(new WebViewClient());
    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    //mPageURL = "http://beta.html5test.com/";
    mWebView.loadUrl(mPageURL);
}

现在我已经开始工作了,但是我想点击一个菜单项来调用loadWebViewContent()来加载不同的页面。

我的NavigationDrawerFragment

中有一个onClick侦听器设置
@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
            Toast.makeText(getActivity(), "test"+position, Toast.LENGTH_LONG).show();
        }

但我无法弄清楚如何从这里调用函数,或者如果需要,需要做些什么来将loadWebViewContent()移动到片段(因为它是一个菜单的东西,我&# 39;对此我可以),但据我所知,WebView归Activity所有,所以我仍然需要做一些我没做的事情来访问函数中的内容并告诉它加载网址。

非常感谢任何帮助或指向正确的方向,谢谢。

1 个答案:

答案 0 :(得分:1)

您可以从片段到活动进行一次回调,例如

 public class NavigationDrawerFragment{
        private Callback mCallback;

        public void setCallback(Callback callback){
            mCallback = callback;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
            Toast.makeText(getActivity(), "test"+position, Toast.LENGTH_LONG).show();
            mCallback.openUrl("your url");
        }

        public interface CallBack{
            public void openUrl(String urlToOprn);
        }

    }

在你的活动中实现这个界面,如 -

 public MainActivity extends Activity implements Callback{   
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_my);

                mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);
                mNavigationDrawerFragment.setCallback(this);
            ------you code from here

            }

            @Override
            public void openUrl( String urlToOpen){
                mPageURL = urlToOpen;
                loadWebViewContent();
            }   

        }