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

The most common way to create and center a Button View in android RelativeLayout is by adding the button in XML layout and using android:layout_centerInParent="true"attribute to center the button.

But there are times we will need to create android button dynamically and center it in a RelativeLayout, below is a code sample we can use to achieve this.

We will create an empty root RelativeLayout in the layout file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

</RelativeLayout>

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);

        RelativeLayout rootViewLayout = (RelativeLayout)findViewById(R.id.root_layout);

        RelativeLayout.LayoutParams centerRel = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        centerRel.setMargins(24, 24, 24, 24);
        centerRel.addRule(RelativeLayout.CENTER_IN_PARENT);

        centerButton.setLayoutParams(centerRel);
        rootViewLayout.addView(centerButton);

    }
}

As can be seen in the code above, the addRule()method with RelativeLayout.CENTER_IN_PARENTis used to center the created android button.

This code snippet does not only work with Button View, you can use it to center any other android View component in a RelativeLayout.

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.