Add padding attribute padding left, padding right, padding top, padding bottom on textview.
Padding are also known as automatic text spacing applied through application developer to adjust textview text from left, right, top, bottom sides by setting paddings. So here is the complete step by step tutorial for Android set textview padding programmatically tutorial.
Android set textview padding programmatically tutorial.
Code for MainActivity.java file.
package com.textviewpaddingprogrammatically_android_examples.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView STEXT;
Button SBUTTON;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
STEXT = (TextView)findViewById(R.id.textView1);
SBUTTON = (Button)findViewById(R.id.button1);
SBUTTON.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
STEXT.setPadding(20, 20, 20, 20);
}
});
}
}
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.textviewpaddingprogrammatically_android_examples.com.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" android:background="#6afdd2" /> <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="41dp" android:text="Click Here to set padding programmatically on TextView" /> </RelativeLayout>
Screenshots: