Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change EditText content with Javascript?

We have a button in HTML. When the user clicks it, the value of my specific EditText should change, but it doesn't.

Code:

class ActivityTest extends Activity {

    TextView textView1;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        WebView webView = (WebView) findViewById(R.id.webView);
        webView.loadUrl("file:///android_res/raw/htmlimages.html");
        webView.addJavascriptInterface(new MyTest(), "Scripts");
        webView.getSettings().setJavaScriptEnabled(true);
        textView1 = (TextView) findViewById(R.id.textView1);
    }


    public class MyTest {

        void setText(String string) 
        {
            textView1.setText(string);
        }
    }
}
like image 513
hosseinAmini Avatar asked May 07 '14 05:05

hosseinAmini


People also ask

What is the difference between an EditText and a TextView?

EditText is used for user input. TextView is used to display text and is not editable by the user. TextView can be updated programatically at any time.

How do I change my EditText value?

This example demonstrates how do I set only numeric value for editText in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

Assuming that your html part is correct one thing that you need to do is make ui calls on the main thread.

so your code:

void setText(String string) 
{
   textView1.setText(string);
}

should be

@JavascriptInterface
public void setText() {
  runOnUiThread(new Runnable() {            
     @Override
     public void run() {
        textView.setText("Testing text");       
     }
  });       
}
like image 137
Karthik Avatar answered Sep 29 '22 20:09

Karthik