Hello
Hello

Reputation: 119

AddView cause crash android

Here is the code that work : In the code below everything work, but when i try to add a second view it crashes.

public void ClearAllV() {

    ImageView IM2 = new ImageView(this);


    HorizontalScrollView SW = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1); 

    HorizontalScrollView.LayoutParams lp = new HorizontalScrollView.LayoutParams(
            HorizontalScrollView.LayoutParams.WRAP_CONTENT,
            HorizontalScrollView.LayoutParams.WRAP_CONTENT);


     SW.removeAllViews();

      IM2.setImageResource(R.drawable.have_fun);
      SW.addView(IM2, lp);



}

But if i try to add a second imageview like the one below it crash,

public void ClearAllV() {

    ImageView IM2 = new ImageView(this);
            ImageView IM3 = new ImageView(this);


    HorizontalScrollView SW = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1); 

    HorizontalScrollView.LayoutParams lp = new HorizontalScrollView.LayoutParams(
            HorizontalScrollView.LayoutParams.WRAP_CONTENT,
            HorizontalScrollView.LayoutParams.WRAP_CONTENT);


     SW.removeAllViews();
          IM3.setImageResource(R.drawable.have_fun);
      IM2.setImageResource(R.drawable.have_fun);
      SW.addView(IM2, lp);
      SW.addView(IM3, lp);


}

Upvotes: 0

Views: 1212

Answers (1)

Jave
Jave

Reputation: 31846

The ScrollView and HorizontalScrollView should only hold one child.
Usually you would have a LinearLayout as the only child of the HorizontalScrollView, and add your views to that.

From the ScrollView-documentation:

A ScrollView is a FrameLayout, meaning you should place one child in it containing the entire contents to scroll;
[...]
A child that is often used is a LinearLayout in a vertical orientation, presenting a vertical array of top-level items that the user can scroll through

Note that this is about the ScrollView (not the HorizontalScrollView (the hsv doc says the same thing but with horizontal instead of vertical), and thus mentions a vertical layout.

Upvotes: 3

Related Questions