Place a view to right side of another view in relativelayout programmatically

How to create view to right side of selected view dynamically jump on button click.

In this tutorial we are moving a textview at application run time and setting up view to right side of selected button. So here is the complete step by step tutorial for Place a view to right side of another view in relativelayout programmatically.

android-project-download-code-button

How to Place a view to right side of another view in relativelayout programmatically.

Code for MainActivity.java file.

 package com.placeviewtoright_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;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView textview;
 Button button;
 LayoutParams layoutparams;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 textview = (TextView)findViewById(R.id.textView1);
 button = (Button)findViewById(R.id.button1);
 
 layoutparams = (LayoutParams)textview.getLayoutParams();
 
 button.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 layoutparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
 layoutparams.addRule(RelativeLayout.RIGHT_OF, button.getId());
 layoutparams.addRule(RelativeLayout.ALIGN_BASELINE, button.getId());
 
 textview.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.placeviewtoright_android_examples.com.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="TextView"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:background="#01eefd" />

 <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="Button" />

</RelativeLayout>

Screenshots:

Place a view to right side of another view in relativelayout programmatically

right view-2

Click here to download Place a view to right side of another view in relativelayout programmatically project.

Leave a Reply

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