TextView is a widget in android to show Text in the formatted and unformatted text.Here in the tutorial, we are going learn about changing the TextView on click events of a button.

Step 1: Open up a project and name it as you like here in this tutorial I am naming it example.Drag and Drop TextView and Button from Widgets from the palette or this XML code for design part.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bytelogs.example.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click ME" android:textAppearance="?android:textAppearanceLarge" android:id="@+id/button" android:background="@color/colorAccent" android:textColor="#ffff" android:layout_centerVertical="true" /> <TextView android:id="@+id/textView" android:textAppearance="?android:textAppearanceLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/button" android:layout_centerHorizontal="true" android:layout_marginBottom="101dp" android:text="On Intitial TextView" /> </RelativeLayout>
Step 2: Create an object of TextView and Button and type cast it to TextView and Button respectively.Make OnClickListener for the button as shown.
Step 3: Call SetText method by using TextView object which you declared in Step:1.
package com.bytelogs.example; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView textView = (TextView)findViewById(R.id.textView); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { textView.setText("Text Changed OnClick"); } }); } }
Decode The Code: Here we are changing the TextView when Button is clicked.Initial, we made TextView and Button in designing part in the XML or it can be made by using drag and drop.Next, we declared an object of Textiew and Button in the MainActivity.java file.We made an OnclickListener for Button using object of a button.Lastly, we have set the text to TextView using object of TextView by calling SetText() method.
Leave a Comment