【安卓开发——点击事件】

本文探讨了Android应用中如何在XML布局文件中使用onClick事件与在Java代码中动态修改TextView内容的两种方法,重点讲解了TextView和Button的实例,并展示了如何在MainActivity中通过Java代码控制按钮点击后的文字变化。
摘要由CSDN通过智能技术生成
<?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">

    <!--
        两种绑定点击事件的方法:
            - 在XML中 onClick
            - 在JAVA代码中
    -->

    <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 {
//    自动补全:ctrl + shift + o
//    自动生成变量 alt + o

    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("牛气冲天");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值