Android的JavascriptInterface问题 [英] Android JavascriptInterface problem

查看:247
本文介绍了Android的JavascriptInterface问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Android的初学者。我想在活动网页视图JavaScript调用JavaScript的接口类来改变一个TextView值。有一个web视图,并在活动布局一个TextView。

I am an Android beginner. I am trying to change a textview value in an activity in a webview javascript call to javascript interface class. There is a webview and a textview in the activity layout.

MyWebActivity

public class MyWebActivity extends Activity {
    ...
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String url =  "http://myurl...";
        webview = (WebView) findViewById(R.id.webview);

        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebChromeClient(new WebChromeClient());
        webview.loadUrl(url);

        webview.addJavascriptInterface(new JsInterface(this), "Android");
    }
    ...
}

JsInterface.java

public class JsInterface {
        ...
       public void setUIText()
       {
             TextView textView1  = (TextView) ((Activity) mContext).findViewById(R.id.textView1);

            /*This line not work*/
        textView1.setText("Hello"); 

            /*This line work*/  
            Toast.makeText(mContext, textView1.getText(), Toast.LENGTH_SHORT).show();
       }
}

HTML文件

Android.setUIText();

接着的问题是,当我叫 Android.setUIText()在HTML文件中,它触发JsInterface的setUIText,我不能设置为<$ C文本$ C> textView1 ,但我可以用得到textView1的文字的getText()

Then problem is, when I call Android.setUIText() in the html file, it trigger the JsInterface's setUIText, and I cannot set the text for the textView1, but I can get the textView1's text using getText().

什么原因?我怎样才能解决这个问题?

What's the reason? How can I fix it?

推荐答案

就在添加这些行您的 setUIText 功能

Just add these lines in your setUIText Function

      public void setUIText()
      {
           final String msgeToast = toast + newToast;           
           myHandler.post(new Runnable() {
               @Override
               public void run() {
                   // This gets executed on the UI thread so it can safely modify Views
                   myTextView.setText(msgeToast);
               }
           });
           Toast.makeText(mContext, textView1.getText(), Toast.LENGTH_SHORT).show();
      }  

这篇关于Android的JavascriptInterface问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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