在android应用程序中,有时要用到很多的按钮元件,每个按钮都要有一个监听事件,为了让代码看起来干净简洁,并节省一些内存,我们可以用一个监听器(Listener)来实现多个按钮的onClick监听,下面是一个具体的例子:
package com.android;import android.app.Activity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;public class IntentSelectActivity extends Activity implements View.OnClickListener{    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                Button button1 = (Button)findViewById(R.id.btn1);        Button button2 = (Button)findViewById(R.id.btn2);        Button button3 = (Button)findViewById(R.id.btn3);        button1.setOnClickListener(this);        button1.setTag(1);        button2.setOnClickListener(this);        button2.setTag(2);        button3.setOnClickListener(this);        button3.setTag(3);            }    public void onClick(View v){    int tag = (Integer) v.getTag();    switch(tag){    case 1:            Intent music = new Intent(Intent.ACTION_GET_CONTENT);            music.setType("audio/*");            startActivity(Intent.createChooser(music, "Select music"));    break;    case 2:    Intent dial = new Intent();    dial.setAction("android.intent.action.CALL");    dial.setData(Uri.parse("tel:13428720000"));    startActivity(dial);    break;    case 3:    Intent wallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);            startActivity(Intent.createChooser(wallpaper, "Select Wallpaper"));    break;    default :    break;    }    }}

这段代码用三个按钮实现了三个Intent意图:音乐播放、自动拨号、背景选择。只用了一个onClick处理,这样代码看起来简洁了很多。

备注,Intent的属性写法与常数写法:

  • 属性写法
    Intent dial = new Intent();
    dial.setAction("android.intent.action.CALL");
  • 常数写法
    Intent wallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
    Intent music = new Intent(Intent.ACTION_GET_CONTENT);

在Intent类中,定义了action的常数。在记忆技巧上,可以用 xxx对应到ACTION_xxx 的方式记。例如:

CALL(android.intent.action.CALL)就是ACTION_CALL(Intent.ACTION_CALL)。

程序运行效果为:
Android 用一个监听器实现多个监听_第1张图片Android 用一个监听器实现多个监听_第2张图片


转载请注明出处:http://blog.csdn.net/imyang2007/article/details/7616075



更多相关文章

  1. 点击事件XML里的写法
  2. Android横竖屏的写法、及savedInstanceState的使用
  3. android ViewHolder模式超简洁写法
  4. Android Studio 活动的最佳实践 知晓当前是在哪一个活动 随时随
  5. 第三十六天 一乐在其中—Android的按钮单击事件及监听器的实现方
  6. Android中点击事件的四种写法详解
  7. Android监听器实现(二)Broadcast方式对通话状态(来电,拨号,挂机)的
  8. Android中为Button注册监听器最常用的两种方法
  9. android各种返回写法

随机推荐

  1. Android软硬整合技术(HAL&Framework)
  2. Android Project和app中两个build.gradle
  3. 关于Android SDK 文档的一点小错误 Galle
  4. Android中的Adapter 详解(三)
  5. android 工程师 你必须知道的
  6. Android H5和App交互以及打开图库上传图
  7. 通读Android文档系列 ONE
  8. 一篇文章带你了解 Android 消息机制的原
  9. Android之drawable和mipmap目录区别
  10. 【多图】Google工程师解析Android系统架