Android 用一个监听器实现多个监听
16lz
2021-01-23
在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)。
程序运行效果为:
转载请注明出处:http://blog.csdn.net/imyang2007/article/details/7616075
更多相关文章
- 点击事件XML里的写法
- Android横竖屏的写法、及savedInstanceState的使用
- android ViewHolder模式超简洁写法
- Android Studio 活动的最佳实践 知晓当前是在哪一个活动 随时随
- 第三十六天 一乐在其中—Android的按钮单击事件及监听器的实现方
- Android中点击事件的四种写法详解
- Android监听器实现(二)Broadcast方式对通话状态(来电,拨号,挂机)的
- Android中为Button注册监听器最常用的两种方法
- android各种返回写法