Help with Android LinearLayout or RelativeLayout
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);
}
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!
Did you try setting layout orientation to verticcal:
mLinearLayout.setOrientation(1);
you can set the orientation of the linear layout object to vertical
精彩评论