0

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);
            }
        });
2
  • Is the value of HomeContainer correct at that point? Commented Dec 30, 2013 at 21:53
  • Yes, HomeContainer is a LinearLayout and correct. At that point, when I click my button, it adds a new TextView. But when I refresh webview, it gets source but does not add TextView. So annoying. Also I tried that one, TextView A = (TextView) getLayoutInflater().from(this.getParent()).inflate(R.layout.note_nick, null); ((Home)this.getParent()).HomeContainer.addView(A); Commented Dec 30, 2013 at 21:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow thank you man! Can't vote since I don't have enough reputation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.