问题
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();
}
}
the html file
Android.setUIText();
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?
回答1:
You cannot do this.
javascript interface run in a new thread (not in the main).
So, to change your UI (the textfield owned by MyWebActivity
), you need to use an handler to re-Synchronize events.
step:
- create an handler in your
MyWebActicity
. - In javascript interface in the method that should change your textfield send an empty message to your MyWebActivity. (ex:
hrefresh.sendEmptMessage(MyHandler.REFRESH_TEXTFIELD)
). - manage the empty message in your handler, that will call a method in your
MyWebActivity
that will change the textfield
回答2:
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();
}
回答3:
You can use
myTextView.post(...
as well.
回答4:
Try this:
final TextView textView1 = (TextView) ((Activity) mContext).findViewById(R.id.textView1);
((Activity) mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
textView1.setText("Hello");
}
}
来源:https://stackoverflow.com/questions/6758604/android-javascriptinterface-problem