views:

512

answers:

3

I need to create two views programmatically (because I need to access the ondraw of one of the views). For some reason, no matter what I do to add the views to the contentview, they don't show up vertically stacked, one below the other.

I can do it just fine using the XML using a RelativeLayout and layout positioning, but with the XML I can't create a view object and overload the ondraw method.

What am I doing wrong with the programmatic approach, and how do I solve this problem?

LinearLayout mLinearLayout;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create a LinearLayout in which to add the ImageView
        mLinearLayout = new LinearLayout(this);

        TextView tv = new TextView(this);
            tv.setBackgroundColor(0xff333333);
        tv.setText("Enter your member number:");
        tv.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));



        DrawableView i = new DrawableView(this);
        i.layout(0,40,0,0);
        i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));

        mLinearLayout.addView(tv);
        mLinearLayout.addView(i,300,300);
        setContentView(mLinearLayout);
    }
+1  A: 

Hi

you can set the orientation of the linear layout object to vertical

thanks

Mina Samy
+1  A: 

There appear to have two issues, though it is harder to debug this code than the XML.

First, you failed to set the Orientation to Vertical for the linear layout. For a horizontal orientation, everything will be one line. For a vertical layout, each widget will be on separate line going from the top to the bottom.

Second, the "Fill Parent" looks suspicious. Any fill parent, unless a Relative Layout or absolute sizing prevents it, takes over everything and hides all other widgets. It's almost always the wrong solution. Try using a weight instead.

You might consider getting this exactly how you like in XML first, and then converting it to a programmatic set-up, keeping the conversion as mechanical as possible. Good luck!

Charles Merriam
+1  A: 

Did you try setting layout orientation to verticcal:

mLinearLayout.setOrientation(1);

Suresh
That fixed it, thanks a lot!
PeEll
@PeEll: If that fixed it, you may want to mark this as the correct answer to give Suresh credit.That said, I strongly suggest using mLinearLayout.setOrientation(VERTICAL) rather than mLinearLayout.setOrientation(1). This will improve your code's readability.
Jim Kiley