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?