Android change TextView width height programmatically

Set textview height (layout_height) ,width(layout_width)programmatically in android on button click using  LayoutParams.

With the help of LayoutParams developer can increase or decrease textview hight on application run time using MainActivity.java programming file. So here is the complete step by step tutorial for Android change TextView width height programmatically.

android-project-download-code-button

Android change TextView width height programmatically.

Code for MainActivity.java file.

 package com.textviewwidthprogrammatically;

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


public class MainActivity extends Activity {

 Button bt1;
 TextView Txt1;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 bt1 = (Button)findViewById(R.id.button1);
 Txt1 = (TextView)findViewById(R.id.textView1);
 final LayoutParams layoutparams = (RelativeLayout.LayoutParams) Txt1.getLayoutParams();
 
 bt1.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 layoutparams.width = 400;
 layoutparams.height = 300;
 
 Txt1.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.textviewwidthprogrammatically.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="TextView Sample Text"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:background="#fe8401" />

 <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 change TextView Width" />
 
</RelativeLayout>

Screenshot:

width-heigh

Android change TextView width height programmatically

Click Here to Download Android change TextView width height programmatically project.

Leave a Reply

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