JS调用函数从静态片段的WebView [英] Call JS function in webview from Static fragment

查看:122
本文介绍了JS调用函数从静态片段的WebView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个表格活动这是自动设置为我时,我选择了固定标签+ Swype输入导航型作响我的项目。在每个标签我加载了一个,基于标签更改URL的WebView。在一个选项卡中,虽然我想调用一个JS函数,生活在页面的WebView是要对。我试过各种各样的事情,没有运气,JS的功能的作品,但由于某种原因,它不会被调用。

在下面的code的网址是不是我在实际使用的网址,也参考这里是JS功能

 函数callFromActivity(MSG){
    的document.getElementById(MYTEXT)的innerHTML =味精。
}

公共类MainActivity扩展FragmentActivity实现ActionBar.TabListener {

/ **
 *在{@link android.support.v4.view.PagerAdapter},将提供
 *对于每个部分的片段。我们使用
 * {@link android.support.v4.app.FragmentPagerAdapter}衍生物,它
 *将让每一个加载的片段记忆。如果这成为过记忆
 *密集,它可能是最好切换到
 * {@link android.support.v4.app.FragmentStatePagerAdapter}。
 * /
SectionsPagerAdapter mSectionsPagerAdapter;

/ **
 *在{@link ViewPager}将承载部分内容。
 * /
ViewPager mViewPager;

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    //设置操作栏。
    最后的动作条动作条= getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    //创建将返回一个片段为三个的适配器
    //应用程序的主要部分。
    mSectionsPagerAdapter =新SectionsPagerAdapter(getSupportFragmentManager());

    //设置的ViewPager与部分适配器。
    mViewPager =(ViewPager)findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    //当不同部分之间的刷卡,选择相应的
    //标签。我们也可以使用ActionBar.Tab#选择()要做到这一点,如果我们有
    //引用的标签。
    mViewPager.setOnPageChangeListener(新ViewPager.SimpleOnPageChangeListener(){
        @覆盖
        公共无效onPageSelected(INT位置){
            actionBar.setSelectedNavigationItem(位置);
        }
    });

    //对于每个应用程序的章节中,添加一个标签,操作栏。
    的for(int i = 0; I< mSectionsPagerAdapter.getCount();我++){
        //创建与对应于由所定义的页标题文本标签
        //适配器。同时,指定此活动的对象,它实现
        //该TabListener界面,回调(监听程序)进行时
        //这个选项卡中选择。
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(I))
                        .setTabListener(本));
    }
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

@覆盖
公共无效onTabSelected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
    //当选择给定的标签,切换到对应页面
    //该ViewPager。
    mViewPager.setCurrentItem(tab.getPosition());
}

@覆盖
公共无效onTabUnselected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
}

@覆盖
公共无效onTabReselected(ActionBar.Tab选项卡,FragmentTransaction fragmentTransaction){
}

/ **
 * A {@link FragmentPagerAdapter}返回对应的片段
 *章节/标签/页之一。
 * /
公共类SectionsPagerAdapter扩展FragmentPagerAdapter {

    公共SectionsPagerAdapter(FragmentManager FM){
        超(FM);
    }

    @覆盖
    公共片段的getItem(INT位置){
        //的getItem被称为实例化片段给定的页面。
        //返回一个DummySectionFragment(定义为静态内部类
        下图)与页面数量作为其唯一的参数//。
        片段片段=新DummySectionFragment();
        捆绑的args =新包();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,位置+ 1);
        fragment.setArguments(参数);
        返回片段;
    }

    @覆盖
    公众诠释getCount将(){
        //显示5总页数。
        返回5;
    }

    @覆盖
    公共CharSequence的getPageTitle(INT位置){
        区域设置L = Locale.getDefault();
        开关(位置){
            情况下0:
                返回的getString(R.string.title_section1).toUpperCase(升);
            情况1:
                返回的getString(R.string.title_section2).toUpperCase(升);
            案例2:
                返回的getString(R.string.title_section3).toUpperCase(升);
            案例3:
                返回的getString(R.string.title_section4).toUpperCase(升);
            壳体4:
                返回的getString(R.string.title_section5).toUpperCase(升);
        }
        返回null;
    }
}

/ **
 *一个虚拟片段重新presenting应用程序的一部分,但只是
 *显示虚拟文本。
 * /
公共静态类DummySectionFragment扩展片段{
    / **
     *片段参数重新presenting本章节号
     * 分段。
     * /
    公共静态最后弦乐ARG_SECTION_NUMBER =section_number标;
    公共DummySectionFragment(){
    }

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
                             捆绑savedInstanceState){

        查看rootView = inflater.inflate(R.layout.fragment_main_dummy,集装箱,假);
        查看htmlView = inflater.inflate(R.layout.home_wvtc,集装箱,假);
        的WebView WC =(web视图)htmlView.findViewById(R.id.webView1);
        TextView的dummyTextView =(TextView中)rootView.findViewById(R.id.section_label);
        // dummyTextView.setText(Integer.toString(getArguments()调用getInt(ARG_SECTION_NUMBER))。);
        如果(getArguments()。调用getInt(ARG_SECTION_NUMBER)== 1)
        {

            wc.getSettings()setJavaScriptEnabled(真)。
            wc.loadUrl(http://www.example.com/android/index.html);
            wc.loadUrl(JavaScript的:callFromActivity('些味精'));

            wc.setWebViewClient(新WebViewClient(){
                公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                    返回false;
                }
            });

            返回htmlView;
        }
        如果(getArguments()。调用getInt(ARG_SECTION_NUMBER)== 2)
        {

            wc.getSettings()setJavaScriptEnabled(真)。
            wc.loadUrl(http://www.example.com/android/request.html);

            wc.setWebViewClient(新WebViewClient(){
                公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                    如果(网址!= NULL){

                        返回false;
                    } 其他 {
                        返回false;
                    }
                }
            });

            返回htmlView;
        }
        如果(getArguments()调用getInt(ARG_SECTION_NUMBER)== 3)
        {

            wc.getSettings()setJavaScriptEnabled(真)。
            wc.loadUrl(http://www.example.com/android/recent.html);
            wc.setWebViewClient(新WebViewClient(){
                公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                    如果(网址!= NULL){

                        返回false;
                    } 其他 {
                        返回false;
                    }
                }
            });
            返回htmlView;
        }
        如果(getArguments()调用getInt(ARG_SECTION_NUMBER)== 4)
        {

            wc.getSettings()setJavaScriptEnabled(真)。
            wc.loadUrl(http://www.example.com/android/queue.html);
            wc.setWebViewClient(新WebViewClient(){
                公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                    如果(网址!= NULL){

                        返回false;
                    } 其他 {
                        返回false;
                    }
                }
            });
            返回htmlView;
        }
        如果(getArguments()调用getInt(ARG_SECTION_NUMBER)== 5)
        {

            wc.getSettings()setJavaScriptEnabled(真)。
            wc.loadUrl(http://www.example.com/android/webcam.html);
            wc.setWebViewClient(新WebViewClient(){
                公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
                    如果(网址!= NULL){

                        返回false;
                    } 其他 {
                        返回false;
                    }
                }
            });
            返回htmlView;
        }
        其他 {
            返回rootView;
        }
    }

 }

}
 

解决方案

您应该等到文档加载完成之前执行的Java脚本。您可以使用 WebChromeClient 看加载进度。

 私有类MyWebChromeClient扩展WebChromeClient {

    私人的WebView mWebView;
    公共MyWebChromeClient(的WebView web视图)
    {
        mWebView = web视图;
    }

    @覆盖
    公共无效onProgressChanged(web视图查看,诠释newProgress){
        super.onProgressChanged(查看,newProgress);
        如果(newProgress == 100){
            mWebView.loadUrl(JavaScript的:callFromActivity('些味精'));
        }
    }
}
 

设置 MyWebChromeClient 的WebView

  wc.getSettings()setJavaScriptEnabled(真)。
wc.loadUrl(http://www.example.com/android/index.html);
wc.setWebChromeClient(新MyWebChromeClient(WC));
 

I am trying to have a tabular activity which is automatically setup for me when I creaked my project by selecting the navigation type of "fixed tabs + swype". In each tab I load up a webview that changes URL based on tab. In one tab though I want to call a JS function that lives on the page the webview is going to. I tried all sorts of things with no luck, the JS function works but for some reason its not being called.

The url in the code below is not the URL I'm actually using, also for reference here is the JS function

function callFromActivity(msg){
    document.getElementById("mytext").innerHTML = msg;
}

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 5 total pages.
        return 5;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            case 3:
                return getString(R.string.title_section4).toUpperCase(l);
            case 4:
                return getString(R.string.title_section5).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";
    public DummySectionFragment() {
    }

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

        View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
        View htmlView =inflater.inflate(R.layout.home_wvtc,container,false);
        WebView wc = (WebView) htmlView.findViewById(R.id.webView1);
        TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
        // dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
        if(getArguments().getInt(ARG_SECTION_NUMBER) == 1 )
        {

            wc.getSettings().setJavaScriptEnabled(true);
            wc.loadUrl("http://www.example.com/android/index.html");
            wc.loadUrl("javascript:callFromActivity('some msg')");

            wc.setWebViewClient(new WebViewClient(){
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }
            });

            return htmlView;
        }
        if(getArguments().getInt(ARG_SECTION_NUMBER) == 2 )
        {

            wc.getSettings().setJavaScriptEnabled(true);
            wc.loadUrl("http://www.example.com/android/request.html");

            wc.setWebViewClient(new WebViewClient(){
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url != null ) {

                        return false;
                    } else {
                        return false;
                    }
                }
            });

            return htmlView;
        }
        if(getArguments().getInt(ARG_SECTION_NUMBER) == 3 )
        {

            wc.getSettings().setJavaScriptEnabled(true);
            wc.loadUrl("http://www.example.com/android/recent.html");
            wc.setWebViewClient(new WebViewClient(){
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url != null ) {

                        return false;
                    } else {
                        return false;
                    }
                }
            });
            return htmlView;
        }
        if(getArguments().getInt(ARG_SECTION_NUMBER) == 4 )
        {

            wc.getSettings().setJavaScriptEnabled(true);
            wc.loadUrl("http://www.example.com/android/queue.html");
            wc.setWebViewClient(new WebViewClient(){
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url != null ) {

                        return false;
                    } else {
                        return false;
                    }
                }
            });
            return htmlView;
        }
        if(getArguments().getInt(ARG_SECTION_NUMBER) == 5 )
        {

            wc.getSettings().setJavaScriptEnabled(true);
            wc.loadUrl("http://www.example.com/android/webcam.html");
            wc.setWebViewClient(new WebViewClient(){
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url != null ) {

                        return false;
                    } else {
                        return false;
                    }
                }
            });
            return htmlView;
        }
        else {
            return rootView;
        }
    }

 }

}

解决方案

You should wait for the document load complete before execute the java script. You can use a WebChromeClient to watch the load progress.

private class MyWebChromeClient extends WebChromeClient {

    private WebView mWebView;
    public MyWebChromeClient(WebView webView)
    {
        mWebView = webView;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        if (newProgress == 100) {
            mWebView.loadUrl("javascript:callFromActivity('some msg')");
        }
    }
}

set the MyWebChromeClient to WebView

wc.getSettings().setJavaScriptEnabled(true);
wc.loadUrl("http://www.example.com/android/index.html");
wc.setWebChromeClient(new MyWebChromeClient(wc));

这篇关于JS调用函数从静态片段的WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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