简体   繁体   中英

Programmatically Center LinearLayout within another LinearLayout

I need to place two TextViews side by side inside a centered view.

I tried asking a similar question yesterday, only with relative layouts. I've made a lot of progress since switching to linear layout for the parent of the two TextViews, so I'd like to see if anyone can add the final component.

Here's what I have:

public void addTableLink(String s, String s1, int g, LinearLayout L, int fsize, int textColor, int backgroundColor, int lpad, int tpad, final String section, final String selection){

    LinearLayout ll = new LinearLayout(this);

    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setGravity(Gravity.CENTER_VERTICAL);

    ll.setLayoutParams(new LinearLayout.LayoutParams(400, 30, Gravity.CENTER_HORIZONTAL));

    ll.setBackgroundColor(backgroundColor);

    TextView tv1 = new TextView(this);
    TextView tv2 = new TextView(this);

    tv1.setText(s);
    tv2.setText(s1);

    tv1.setTextSize(fsize);
    tv2.setTextSize(fsize);

    tv1.setTextColor(textColor);
    tv1.setTextColor(textColor);

    ll.addView(tv1);
    ll.addView(tv2);

    L.addView(ll);

}

Which gives me this:

这是结果

All I need now is to get that "Company: Google" section (the white part) to be centered above, while keeping the text left aligned.

Any suggestions?

Solved it. Here's the code, all you need to do is center the view that is passed to this method (LinearLayout L) and it works great (the secret is setting the new view to horizontal):

public void addTableLink(String s, String s1, int g, LinearLayout L, int fsize, int textColor, int backgroundColor, int lpad, int tpad, final String section, final String selection){

    LinearLayout ll = new LinearLayout(this);

    ll.setOrientation(LinearLayout.HORIZONTAL);
    ll.setGravity(Gravity.CENTER_VERTICAL);

    ll.setLayoutParams(new LinearLayout.LayoutParams(400, 30));

    ll.setBackgroundColor(backgroundColor);

    TextView tv1 = new TextView(this);
    TextView tv2 = new TextView(this);

    tv1.setText(s);
    tv2.setText(s1);

    tv1.setPadding(lpad, tpad, 0, 0);

    tv1.setTextSize(fsize);
    tv2.setTextSize(fsize);

    tv1.setTextColor(textColor);
    tv2.setTextColor(Color.BLUE);
    tv2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {                  
            setMainView(section, selection);
            setTitle(section);
         }
        });

    ll.addView(tv1);
    ll.addView(tv2);

    L.addView(ll);

}

在此处输入图片说明

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