在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