简体   繁体   中英

Aligning a Linear Layout within a RelativeLayout to the Center and to the Left

Currently I have tried aligning my Linear Layout to the left and center but currently cannot get this to work. See code below:

    CustomLinearLayout sideMenu = new CustomLinearLayout(this);

    RelativeLayout.LayoutParams sideMenuParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,  LayoutParams.WRAP_CONTENT);
    sideMenuParams.addRule(RelativeLayout.CENTER_VERTICAL);
    sideMenuParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);   

    sideMenu.setLayoutParams(sideMenuParams);   
    sideMenu.setOrientation(LinearLayout.VERTICAL);
    sideMenu.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    sideMenu.setBackgroundColor(Color.TRANSPARENT);
    //sideMenu.setGravity(Gravity.CENTER);

    sideMenu.addView(AppSoups);
    sideMenu.addView(salads);
    sideMenu.addView(ribs);
    sideMenu.addView(favorites);
    sideMenu.addView(sandwiches);
    sideMenu.addView(sides);
    sideMenu.addView(desserts);

    RelativeLayout screenLayout = new RelativeLayout(this);
    screenLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
    screenLayout.setBackgroundResource(R.drawable.body_bkgd);
    screenLayout.addView(sideMenu);

    setContentView(screenLayout);

CustomLinearLayout is just a class that extends LinearLayout to do some custom drawing. Anyway what I am doing wrong here? So far it aligns left and to the top of the relative layout but i cannot get it to center. Just as a side note both or either or of my rules do not work in conjuction with setting the LinearLayout to the center(i have it commented out in the code). Finally the views that i am adding to the linear layout are just textviews - just FYI(code not shown)

I think you are "overriding the layout params you've set in line 5 with new layout params you are setting in line 7, so

    sideMenuParams.addRule(RelativeLayout.CENTER_VERTICAL);
    sideMenuParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);  

are not really taking affect

In here

screenLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 

try changing the WRAP_CONTENT to FILL_PARENT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM