Android 用一个监听器实现多个监听

来源:互联网 发布:格拉姆矩阵 编辑:程序博客网 时间:2024/05/02 02:22
 633人阅读 评论(1) 收藏 举报
在android应用程序中,有时要用到很多的按钮元件,每个按钮都要有一个监听事件,为了让代码看起来干净简洁,并节省一些内存,我们可以用一个监听器(Listener)来实现多个按钮的onClick监听,下面是一个具体的例子:
[java] view plaincopy
  1. package com.android;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.net.Uri;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9.   
  10. public class IntentSelectActivity extends Activity implements View.OnClickListener{  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.           
  17.         Button button1 = (Button)findViewById(R.id.btn1);  
  18.         Button button2 = (Button)findViewById(R.id.btn2);  
  19.         Button button3 = (Button)findViewById(R.id.btn3);  
  20.         button1.setOnClickListener(this);  
  21.         button1.setTag(1);  
  22.         button2.setOnClickListener(this);  
  23.         button2.setTag(2);  
  24.         button3.setOnClickListener(this);  
  25.         button3.setTag(3);  
  26.           
  27.   
  28.     }  
  29.     public void onClick(View v){  
  30.         int tag = (Integer) v.getTag();  
  31.         switch(tag){  
  32.         case 1:  
  33.             Intent music = new Intent(Intent.ACTION_GET_CONTENT);  
  34.             music.setType("audio/*");  
  35.             startActivity(Intent.createChooser(music, "Select music"));  
  36.             break;  
  37.         case 2:  
  38.             Intent dial = new Intent();  
  39.             dial.setAction("android.intent.action.CALL");  
  40.             dial.setData(Uri.parse("tel:13428720000"));  
  41.             startActivity(dial);  
  42.             break;  
  43.         case 3:  
  44.             Intent wallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);  
  45.             startActivity(Intent.createChooser(wallpaper, "Select Wallpaper"));  
  46.             break;  
  47.         default :  
  48.             break;  
  49.         }  
  50.   
  51.     }  
  52. }  

这段代码用三个按钮实现了三个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)。

程序运行效果为:


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