Set textview margin programmatically in android

Dynamically set android: layout marginLeft=””, layout marginTop, layout marginRight, layout marginBottom on textview.

Textview widget supports multiple types of margin attributes via activity_main.xml layout file but android application developer can also apply margin attributes on textview using programming coding file. So here is the complete step by step tutorial for Set textview margin programmatically in android.

android-project-download-code-button

How to Set textview margin programmatically in android.

Code for MainActivity.java file.

 package com.textviewmarginprogrammatically_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 {

 Button SetMarginButton;
 TextView ApplyMarginTextView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 SetMarginButton = (Button)findViewById(R.id.button1);
 ApplyMarginTextView = (TextView)findViewById(R.id.textView1);
 final LayoutParams layoutparams = (RelativeLayout.LayoutParams)ApplyMarginTextView.getLayoutParams();
 
 SetMarginButton.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 layoutparams.setMargins(50,50,50,50);

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

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

 <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="Click here to Set textview margin programmatically in android" />

</RelativeLayout>

Screenshots:

Set textview margin programmatically in android

with_margin

Click here to download Set textview margin programmatically in android project.