Android Studio 点击按钮、长按按钮

页面布局

activity_text_view.xml

<?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:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/result"
        android:textSize="30sp"
        android:textColor="#000000"
        android:gravity="center"
        android:background="#FFFFFF"/>
    <Button
        android:id="@+id/btn_top"
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:text="@string/btn_top"
        android:textSize="30sp" />
    <Button
        android:id="@+id/btn_bottom"
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:text="@string/btn_bottom"
        android:textSize="30sp" />
    <Button
        android:id="@+id/btn_long"
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:text="@string/btn_long"
        android:textSize="30sp" />
</LinearLayout>

strings.xml

<resources>
    <string name="app_name">My Application</string>
    <string name="result">这里显示点击结果</string>
    <string name="btn_top">上面的按钮</string>
    <string name="btn_bottom">下面的按钮</string>
    <string name="btn_long">长按按钮</string>
</resources>

TextViewActivity.java

package com.example.myapplication;

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

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class TextViewActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_result;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view);

        tv_result = findViewById(R.id.tv_result);

        findViewById(R.id.btn_top).setOnClickListener(this);
        findViewById(R.id.btn_bottom).setOnClickListener(this);
        findViewById(R.id.btn_long).setOnLongClickListener(view -> {
            tv_result.setText("您点击了长按按钮");
            return true;
        });
    }


    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn_top){
            tv_result.setText("您点击了上面的按钮");
        }else if (view.getId() == R.id.btn_bottom){
            tv_result.setText("您点击了下面的按钮");
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值