zoukankan      html  css  js  c++  java
  • 基于监听的事件处理——Activity本身作为事件监听器

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

    • 这种形式可能造成程序结构混乱,Activity的主要职责应该是完成界面初始化工作,但此时还需要包含事件处理器方法,从而引起混乱。
    • 如果Activity界面类需要实现监听器接口,让人感觉比较怪异。

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

          该程序的界面布局文件如下:

         

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:gravity="center_horizontal"
        tools:context=".ActivityListener" >
        <EditText
            android:id="@+id/show"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:editable="false"
           >
        </EditText>
        <Button
            android:id="@+id/bn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="单击我" />
    </LinearLayout>

       该程序的后台代码如下:

      

    package com.example.studyevent;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    
    public class ActivityListener extends Activity implements OnClickListener {
        EditText show;
        Button bn;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_activity_listener);
            show=(EditText)findViewById(R.id.show);
            bn=(Button)findViewById(R.id.bn);
            //直接使用Activity作为事件监听器
            bn.setOnClickListener(this);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_listener, menu);
            return true;
        }
    
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            show.setText("bn按钮被点击了!");
        }
    
    }

       上面的程序中让Activity类实现了OnClickListener事件监听器接口,从而可以在该Activity类中直接定义事件处理器方法:onClick(View v)(如上面的粗体字代码所示。)。为某个组价添加该事件监听器对象时,直接使用this作为事件监听器对象即可。

          

  • 相关阅读:
    web.xml配置详解
    oracle按时间创建分区表
    cron表达式详解
    临时表
    配置非安装版tomcat服务
    CodeForces 785 D Anton and School
    CodeForces 601B Lipshitz Sequence
    CodeForces 590C Three States BFS
    CodeForces 592D Super M DP
    CodeForces 507E Breaking Good 2维权重dij
  • 原文地址:https://www.cnblogs.com/wolipengbo/p/3407037.html
Copyright © 2011-2022 走看看