Search code examples
javaandroidlayoutalignment

How to horizontally align an inner layout


Within a dialog I am trying to create a LinearLayout containing first a TextView and second a GridLayout programmatically (not by defining an xml-layout). How can I make the inner GridLayout center horizontally within the outer LinearLayout.

Desired_layout:

desired_layout

For the inner TextView it is quite simple (via setGravity). But I cannot figure out how to do it for the GridLayout. I messed around with setting LayoutParams to the outer layout and to the inner layout, but could not find a way.

btw: I understand that the difference between the xml-attributes android:layout_gravity and android:gravity is basically defining layout for the containing child views and for the view itself, but why is there no corresponding java method like setLayoutGravity() but only setGravity()?

LinearLayout outerLayout = new LinearLayout(getContext());
outerLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtView = new TextView(getContext());
txtView.setText("Hello world");
txtView.setGravity(Gravity.CENTER_HORIZONTAL);
GridLayout innerLayout = _buildMyGridLayout(getContext());
//what to do with the innerLayout?
outerLayout.addView(txtView);
outerLayout.addView(innerLayout);

Solution

    1. Create instance of LinearLayout.LayoutParams
    2. Set gravity via public field gravity, see also Gravity
    3. Use layout params instance for GridLayout (use addView method with LayoutParams)