jason
jason

Reputation: 7164

Multiple WebViews in a single Activity

I'm using WebViews to display multiple animated gifs. Here is my code :

  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_myactivity);

        Intent myintent = getIntent();
        String myWord = myintent.getStringExtra("word");

        LinearLayout linearLayout= new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setLayoutParams(new AbsListView.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT,
                AbsListView.LayoutParams.MATCH_PARENT));

        for(int i = 0; i < myKelime.length(); i++)
        {

            WebView wView = new WebView(this);
            //setting image resource
            switch (myWord.charAt(i)){
                case 'a':         wView.loadUrl("file:///android_asset/a.gif");
                    setContentView(wView);
                    break;
                case 'b' :         wView.loadUrl("file:///android_asset/b.gif");
                    setContentView(wView);
                    break;
                case 'c' :         wView.loadUrl("file:///android_asset/c.gif");
                                  setContentView(wView); 
                                                              break;

//goes until z

}
            wView.setLayoutParams(new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT,
                    AbsListView.LayoutParams.WRAP_CONTENT));
            linearLayout.addView(wView);
            //make visible to program
            setContentView(linearLayout);


        }
    }

When I run this code, I get this error :

Unable to start activity ComponentInfo{com.example.mypc.myapp/com.example.mypc.myapp.MyActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

This was working when I was using ImageView instead of WebView.. How can I get rid of this, and display multiple webviews correctly? Thanks.

Upvotes: 0

Views: 773

Answers (2)

jason
jason

Reputation: 7164

When I added this code, it solved :

    if(wView.getParent()!=null)
        ((ViewGroup)wView.getParent()).removeView(wView);

Upvotes: 1

Jas
Jas

Reputation: 3212

You have used setContentView() twice in your code. This might be the reason. It is not recommended to use setContentView() multiple times in same Activity.Try using different Fragments if you need to implement this.

Upvotes: 2

Related Questions