安卓——添加事件处理EventHandle

事件处理有三种方法:

  • 基于监听的方法
  • 基于回调的方法
  • 重写onClick方法

#主页面的XML文件,点击不同按钮展示不同的情况

<?xml version="1.0" encoding="utf-8"?>
<net.onest.eventhandlech0301.MyLinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <Button
        android:id="@+id/btn_normal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="普通的按钮"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et"/>
    <Button
        android:id="@+id/btn_click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="buttonClicked"
        android:text="事件监听器按钮"/>
    <net.onest.eventhandlech0301.MyButton
        android:id="@+id/btn_custom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定义触摸事件回调方法的按钮"/>
    <net.onest.eventhandlech0301.MyImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ball"/>
</net.onest.eventhandlech0301.MyLinearLayout>

1.基于监听

直接通过组件的引用.setXXX的方法设置监听
		//对输入框的键盘事件做处理
        EditText editText = findViewById(R.id.et);
        editText.setOnKeyListener(new View.OnKeyListener() {
   
            @Override
            //KeyEvent键盘事件类型
            public boolean onKey(View v, int keyCode, KeyEvent event) {
   
                Log.e("输入框的按键事件处理方法",event.getNumber() + "");//获取数字按钮的值
                return false;
            }
        });

        Button btnNormal = findViewById(R.id.btn_normal);
        btnNormal.setOnClickListener(this);//MainActivity作为监听器
        btnNormal.setOnTouchListener(new View.OnTouchListener() {
   
            @Override
            //对触摸事件的处理
            public boolean onTouch(View v, MotionEvent event) {
   
                switch (event.getAction())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值