Align a view to right of relativelayout programmatically android

Set any widget to right side inside relativelayout using addRule(RelativeLayout.ALIGN_PARENT_RIGHT) dynamically code on activity run time.

In this tutorial we are setting up button widget view to dynamically at the right side of relativelayout, Because moving views at the activity run time is some times required when application developer bound to developer its whole android app using programmatically method. So here is the complete step  by step tutorial for Align a view to right of relativelayout programmatically android.

android-project-download-code-button

How to Align a view to right of relativelayout programmatically android.

Code for MainActivity.java file.

 package com.alignrightviewrelativelayout_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class MainActivity extends Activity {

 Button left2right;
 LayoutParams layoutarams;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 left2right = (Button)findViewById(R.id.button1);
 
 layoutarams = (LayoutParams)left2right.getLayoutParams();
 
 left2right.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 layoutarams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

 left2right.setLayoutParams(layoutarams);
 }
 });
 }
}

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.alignrightviewrelativelayout_android_examples.com.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Button View" />

</RelativeLayout>

Screenshots :

Align a view to right of relativelayout programmatically android

button-view-right

Click here to download Align a view to right of relativelayout programmatically android project.

Leave a Reply

Your email address will not be published. Required fields are marked *