Search code examples
androidlayouttextviewandroid-relativelayout

Centering multiple textViews programmatically on Android


I have an Open GL ES 2.0 app and am displaying an Android TextView over the top of my GLSurfaceView.

I have the actual textviews displaying OK but now I need to try to centre them.

This is what I have so far:

    text1 = new TextView(this);
    text1.setText("This is some sample text");
    text1.setTextColor(Color.WHITE);
    text1.setTextSize(textSize);

    text2= new TextView(this);
    text2.setText("And this is some more sample text");
    text2.setTextColor(Color.WHITE);
    text2.setTextSize(textSize);

    RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL);

    textLayout = new RelativeLayout(this);
    textLayout.setLayoutParams(textParams);
    textLayout.addView(text1);
    textLayout.addView(text2);

    mainLayout.addView(textLayout);

However, when I run this, only text1 is centered. Text 2 isn't, and starts at the left side of the first (correctly centered) textView. Try as I might, I can't seem to get both of them centered. The following graphic describes what I mean:

(Please note re vertical placement - in my actual results, both TextViews are at the same vertical/'y' position and therefore overlapping - obviously this is expected as I haven't changed the vertical position of the 2nd TextView, but to make things clearer to illustrate, I've moved the 2nd one down manually.......)

enter image description here

The idea I was going with was creating a 'textLayout' to which I could add all of my textViews, then just add that textLayout to my main layout. Thus facilitating the addition and removal of all of the textViews with a single line of code.

Please note that I am not using, and do not wish to use, XML for this - I would like to know how to do this programmatically.

What am I missing?

Edit Here is how I am creating my Main Layout to which I am adding the textView.....

layout = new RelativeLayout(this);
        layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,    LayoutParams.MATCH_PARENT));

Solution

  • When you are adding "RelativeLayout.CENTER_HORIZONTAL" as a rule to your layout params, what you are actually doing is telling textLayout that it should be centered horizontally in your mainLayout (see http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#attr_android:layout_centerHorizontal). In code you should actually do text1.setGravity(Gravity.CENTER) and text2.setGravity(Gravity.CENTER).