How to Center a Button View in a LinearLayout Programmatically in Android

In the previous code example, we showed how to center a button view in a RelativeLayout progammatically in Android.

We will replicate the solution to learn how to center a button in a LinearLayout programmatically in android.

Bear in mind that RelativeLayout centers its child views different from LinearLayout.  RelativeLayout position child Views relative to their parents.

Whereas it is different with LinearLayout. Child Views are position to left, right, top, bottom and center. 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

</androidx.appcompat.widget.LinearLayoutCompat>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button centerButton = new Button(this);
        centerButton.setText("Create & Center");
        centerButton.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        centerButton.setTextColor(Color.WHITE);
        centerButton.setPadding(12, 12, 12, 12);

        LinearLayoutCompat rootViewLayout = (LinearLayoutCompat)findViewById(R.id.root_layout);
        rootViewLayout.setGravity(Gravity.CENTER);
        LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);

        params.setMargins(24, 24, 24, 24);
        params.gravity = Gravity.CENTER_VERTICAL;
        centerButton.setLayoutParams(params);

        rootViewLayout.addView(centerButton);

    }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.