app简单控件了解——按钮——第三种按钮点击方式——MainActivity 实现 View.OnClickListener 接口

如何为按钮添加监听方式总结

 

本文概述:

  • 本文介绍了,在Android中为控件添加监听的三种常见方式

    • 设置控件的onClick属性
    • 采用匿名内部类
    • MainActivity 实现 View.OnClickListener 接口

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

复制代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_click_single"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="指定单独的点击监听器"
            android:textColor="#000000"
            android:textSize="15sp" />

<!--        <Button-->
<!--            android:id="@+id/btn_click_public"-->
<!--            android:layout_width="0dp"-->
<!--            android:layout_height="wrap_content"-->
<!--            android:layout_weight="1"-->
<!--            android:text="指定公共的点击监听器"-->
<!--            android:textColor="#000000"-->
<!--            android:textSize="15sp" />-->

    </LinearLayout>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:text="这里查看按钮的点击结果"
        android:textColor="#000000"
        android:textSize="15sp" />

</LinearLayout>
复制代码

 

 

 

 

 

 

 

 

复制代码
package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    private TextView tv_result; // 声明一个文本视图实例

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取button按钮
       Button button = findViewById(R.id.btn_click_single);

        //为控件注册监听器
        button.setOnClickListener(this);
    }


    @Override
    public void onClick(View v)
    {
        tv_result = findViewById(R.id.tv_result); // 获取名叫tv_result的文本视图

        tv_result.setText("您点击了此按钮_yes"); // 设置文本视图的文本内容
    }
}
复制代码

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @   小白龙白龙马  阅读(48)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示