简体   繁体   中英

Calling AddView in a JavaScriptInterface class

I'm trying to add a textview dynamically to a linear layout. But there is a problem.

In my button, this code works very well:

TextView ASDF = (TextView) getLayoutInflater().inflate(R.layout.note_date, null);
ASDF.setText("TEST");
HomeContainer.addView(ASDF);

But when I try to add this view in a function which called by a JavaScriptInterface class, it does not work. I am using @JavaScriptInterface in order to get my webview's page source. And briefly, I am trying to add new textviews to my layout when web page is loaded in my webview.

So it is like:

public class WebAppInterface
{
     Context mContext;
     WebAppInterface(Context c) {mContext = c;}

     @JavascriptInterface
     public void GetHTML(String html)
     {
         ...
         ...
         TextView ASDF = (TextView) getLayoutInflater().inflate(R.layout.note_date, null);
         ASDF.setText("TEST");
         HomeContainer.addView(ASDF);
     }
}

When I check, I see that webview's source is correct, and also ASDF is not returned null by inflate(), then problem is about addView, I think.

How can I fix that problem?

EDIT: Tried this one, did not work:

TextView ASDF = (TextView) getLayoutInflater().from(this.getParent()).inflate(R.layout.note_nick, null);
ASDF.setText("TEST");
((MainActivity)this.getParent()).HomeContainer.addView(ASDF);

EDIT:

Solved, Thanks to @SimonSays, This will solve your problem:

        runOnUiThread(new Runnable()
        {
            public void run()
            {
                TextView ASDF = (TextView) getLayoutInflater().inflate(R.layout.note_date, null);
                ASDF.setText("TEST");
                HomeContainer.addView(ASDF);
            }
        });

My guess is that the JavaScript method is not executed in the UI thread. Only this thread can modify the UI. You can either use Activity.runOnUiThread() or View.post() to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM