Add rule to button in relativelayout android programmatically

How to set view alignment parent bottom right side dynamically android.

Adding rule means setting up button alignment using programming method using MainActivit.java programming file. So here is the complete step by step tutorial for Add rule to button in relativelayout android programmatically.

android-project-download-code-button

How to Add rule to button in relativelayout android programmatically.

Code for MainActivity.java file.

 package com.addrulebutton_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 AddRule;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 AddRule = (Button)findViewById(R.id.button1);
 
 AddRule.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 LayoutParams layoutparams = (LayoutParams) AddRule.getLayoutParams();
 layoutparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
 layoutparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
 AddRule.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.addrulebutton_android_examples.com.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Add rule to button" />

</RelativeLayout>

Screenshots:

Click here to download Add rule to button in relativelayout android programmatically project.

Leave a Reply

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