Help with Android LinearLayout or RelativeLayout

北战南征 提交于 2019-12-11 01:53:29

问题


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:


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!




回答2:


Did you try setting layout orientation to verticcal:

mLinearLayout.setOrientation(1);




回答3:


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



来源:https://stackoverflow.com/questions/2963414/help-with-android-linearlayout-or-relativelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!