简体   繁体   English

在JavaScriptInterface类中调用AddView

[英]Calling AddView in a JavaScriptInterface class

I'm trying to add a textview dynamically to a linear layout. 我正在尝试动态地将textview添加到线性布局中。 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. 但是当我尝试在JavaScriptInterface类调用的函数中添加此视图时,它不起作用。 I am using @JavaScriptInterface in order to get my webview's page source. 我正在使用@JavaScriptInterface来获取我的webview的页面源代码。 And briefly, I am trying to add new textviews to my layout when web page is loaded in my webview. 简而言之,当我在webview中加载网页时,我正在尝试将新的textview添加到我的布局中。

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. 当我检查时,我看到webview的源是正确的,并且inflate()也没有返回ASDF,然后问题是关于addView,我想。

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: 解决了,感谢@SimonSays,这将解决您的问题:

        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. 我的猜测是JavaScript方法没有在UI线程中执行。 Only this thread can modify the UI. 只有这个线程可以修改UI。 You can either use Activity.runOnUiThread() or View.post() to do so. 您可以使用Activity.runOnUiThread()View.post()来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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