Activity本身作为事件监听器类

这种形式使用Activity本身作为监听器类,可以直接在Activity类中定义事件处理器方法。这种形式非常简洁,但这种做法有两个缺点。

~这种形式可能造成程序结构混乱,Activity的主要职责应该是完成界面初始化工作,但此时还要包含事件处理器方法,从而引起混乱。

~如果Activity界面类需要实现监听器接口,让人感觉比较怪异。


下面的程序使用Activity对象作为事件监听器。

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    EditText show;
    Button bn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        show = (EditText) findViewById(R.id.show);
        bn = (Button) findViewById(R.id.bn);
        //直接使用Activity作为事件监听器
        bn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        show.setText("bn按钮被单击了!");
    }
布局文件如下。

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.lu.activitylistener.MainActivity"
    tools:showIn="@layout/activity_main"
    android:orientation="vertical">

    <EditText
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bn"
        android:text="单击"/>
</LinearLayout>
运行结果如下。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值