Here we will create an app containing a TextView and a Button, and in which text of the TextView changes on clicking the Button.
Step 1: Create a new project and name it textviewexample. Select File -> New -> New Project. Fill the forms and click “Finish” button.
Step 3: Open res -> layout -> xml (or) main.xml and add following code. Here we will create a Button and a TextView in a LinearLayout.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center_vertical|center_horizontal"> <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Before Clicking" android:textColor="#f00" android:textSize="25sp" android:textStyle="bold|italic" android:layout_marginTop="50dp"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#f00" android:padding="10dp" android:text="Change Text" android:textColor="#fff" android:textStyle="bold"/> </LinearLayout>
Step 4: Open app -> java -> package and open MainActivity.java. Add following code in it. Here we will change the text of TextView to ‘Text After Clicking’ when user clicks the Button.
package example.myandroid.textviewexample;
import android.graphics.Color;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
//Declare a TextView and a Button
private TextView textview1;
private Button changeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set the layout
setContentView(R.layout.main);
//Create TextView and Button using their id from xml file
textview1 = (TextView) findViewById(R.id.textview1);
changeText = (Button) findViewById(R.id.button1);
//Set an onClickListener for the Button
changeText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Change Text of TextView when Button is clicked
textview1.setText("Text After Clicking");
}
});
}
}Output:
Now run the app and click on the button. The text of TextView will change to “Text After Clicking” on clicking the button.