安卓给按钮加监听识别

给按钮加监听识别

  • 之前说过了我们要控制组件是要在MainActivity里面写代码
  • 布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <Button
        android:id="@+id/jub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陆"/>
</LinearLayout>

写代码前我们要有一个思路:

  1. 首先,要定义一个组件(按钮)
  2. 通过id找到这个组件(按钮)
  3. 在该组件(按钮)上添加监听事件

代码如下:

ackage com.example.comgzh202116;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button button;//声明一个按钮
    int i=0; //记录点击次数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.jub); //通过id找到按钮

        button.setOnClickListener(new View.OnClickListener() {//添加监听
            @Override
            public void onClick(View v) {
                i++;
                button.setText("点击"+i+"次");
            }
        });
    }
}

没点击
在这里插入图片描述
点击两次
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值