Move RelativeLayout inside view align position CENTER_HORIZONTAL, CENTER_IN_PARENT, CENTER_VERTICAL on button click.
Sometimes application developer needs to move views inside relative Layout using MainActivity.java programming file to setup views position. So here is the complete step by step tutorial for Set another view to center of RelativeLayout Programmatically.
How to Set another view to center of RelativeLayout Programmatically.
Code for MainActivity.java file.
package com.relativelayoutviewprogrammatically_android_examples.com; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { View view; Button BT1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view =(View)findViewById(R.id.view1); BT1 = (Button)findViewById(R.id.button1); final LayoutParams layoutparams = (LayoutParams) view.getLayoutParams(); BT1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { layoutparams.addRule(RelativeLayout.CENTER_VERTICAL); view.setLayoutParams(layoutparams); } }); } }
Code for activity_main.xml layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.relativelayoutviewprogrammatically_android_examples.com.MainActivity" > <View android:id="@+id/view1" android:layout_width="100dp" android:layout_height="100dp" android:background="#04009e"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Set another view to center of RelativeLayout Programmatically" /> </RelativeLayout>
Screenshots: