<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="HELLO"
android:textSize="40sp"
android:gravity="center"
android:padding="20dp"
android:layout_margin="20dp"
android:background="@color/purple_500" />
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="XML中改变文字"
android:padding="10dp"
android:textSize="25sp"
android:onClick="changeText"
android:layout_margin="20dp" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="JAVA代码改变文字"
android:padding="10dp"
android:textSize="25sp"
android:onClick="changeText"
android:layout_margin="20dp" />
</LinearLayout>
package com.example.helloworld;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
button = findViewById(R.id.btn2);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
textView.setText("恭喜发财");
}
});
}
public void changeText(View view) {
textView.setText("牛气冲天");
}
}