Set text alignment vertically center automatically on button click.
Vertical center means to set your textview text into vertically middle of activity screen. Developer can set text alignment using xml file but some times there are special needs so you can also set text alignment using programming file. So here is the complete step by step tutorial for Set TextView Vertically center in android programmatically .
How to Set TextView Vertically center in android programmatically .
Code for MainActivity.java file.
package com.android_examples.com.textviewverticallycenter; 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 VerticalCenter; TextView ST; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ST = (TextView)findViewById(R.id.textView1); VerticalCenter = (Button)findViewById(R.id.button1); VerticalCenter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ST.setGravity(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.android_examples.com.textviewverticallycenter.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="400dp" android:layout_height="300dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Large 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="16dp" android:text="CLICK HERE TO SET TEXTVIEW VERTICALLY CENTER" /> </RelativeLayout>
Screenshot: