Set TextView Text Horizontally center in android programmatically

Set text alignment center in horizontal on button click using gravity function.

Gravity function used in android apps to set gravity of widgets, frames, composite types and layouts.  With the use of this function developer can set textView text alignment automatically center horizontal on button click event. So when you click on button then it will automatically set selected textview alignment center in horizontal. So here is the complete step by step tutorial for Set TextView Text Horizontally center in android programmatically .

android-project-download-code-button

How to Set TextView Text Horizontally center in android programmatically.

Code for MainActivity.java file.

 package com.android_examples.com.textviewhorizontallycenter;

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 {

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

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

 <TextView
 android:id="@+id/textView1"
 android:layout_width="290dp"
 android:layout_height="100dp"
 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="60dp"
 android:text="CLICK HERE TO SET TEXTVIEW HORIZONTALLY" />
 
</RelativeLayout>

Screenshot:

without horizontal

Set TextView Text Horizontally center in android programmatically

Click Here To Download Set TextView Text Horizontally center in android programmatically project.

Leave a Reply

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