Set textview gravity programmatically in android

Dynamically setup TextView inside text gravity on button click using coding file on button click.

TextView gravity means textview widget inside complete text alignment setting up using MainActivity.java programming file. This feature will gives us the facility to adjust text alignment inside textview. You can set text alignment programmatically using setGravity() function. So here is the complete step by step tutorial for Set textview gravity programmatically in android.

android-project-download-code-button

How to Set textview gravity programmatically in android.

Code for MainActivity.java file.

 package com.textviewgravity_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView text;
 Button button;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 text = (TextView)findViewById(R.id.textView1);
 button = (Button)findViewById(R.id.button1);
 
 button.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 text.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
 
 }
 });
 }
}

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

 <TextView
 android:id="@+id/textView1"
 android:layout_width="fill_parent"
 android:layout_height="200dp"
 android:layout_alignLeft="@+id/button1"
 android:layout_alignParentTop="true"
 android:layout_marginTop="42dp"
 android:background="#cbfbc7"
 android:text="TextView Text"
 android:textAppearance="?android:attr/textAppearanceLarge" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="18dp"
 android:text="Click here to set TextView Gravity dynamically" />

</RelativeLayout>

Screenshots:

Set textview gravity programmatically in android

Set textview gravity programmatically in android

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

Leave a Reply

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