安卓回掉方法

安卓的事件处理

1. 基于回调

​ 在XML中定义按钮的事件类型及其处理方法,在java中完成事件处理方法的定义。

<!--在xml中的配置 -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一段文字"
        android:textSize="30sp"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:onClick="changeText"
        >


    </Button>
</LinearLayout>
//主函数中的调用信息 
public void changeText(View view){
        TextView textView = findViewById(R.id.text_view);
        textView.setText(R.string.newstr);
        this.setTitle("这是一个新的标题");
    }

效果:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ECtMAiSf-1628000947602)(/Users/chenshimiao/Library/Application Support/typora-user-images/image-20210803215640833.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fJJdL33t-1628000947604)(/Users/chenshimiao/Library/Application Support/typora-user-images/image-20210803215757366.png)]

2.基于监听接口

​ 实现OnClickListener监听借口,当点击按钮时,通过OnClickListener监听借口触发onCLick()事件。

        Button btn = findViewById(R.id.btn); 
//匿名类
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView textView = findViewById(R.id.text_view);
                textView.setText(R.string.newstr);
                MainActivity.this.setTitle("这是一个新的标题");
            }
        });

(1)步骤

a. 定义一个监听类实现接口(OnClickListener)
b.重写器内部的onClick()方法
c.在将该监听器类注册到被监听到控件上,完成监听

按钮对象.setOnClickListener(OnClickListerner对象);

3.常见的安卓回掉方法

(1).onKeyDown:手机键盘被按下的事件

(2).onKeyUp:手机键盘按下抬起的事件

(3).onTouchEvent:屏幕的触摸事件

(4).onTrackBallEvent:手机中轨迹球的事件

(5).onFocusChanged:焦点改变事件,当某个控件重写了该方法后,焦点发生变化时,会自动调用该方法来处理焦点改变的事件。

前边介绍的前面各种方法都可以在View及Acticity中重写,onFocusChanged却只能在View中重写。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值