歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 用一個監聽器實現多個監聽

Android 用一個監聽器實現多個監聽

日期:2017/3/1 10:21:11   编辑:Linux編程
在Android應用程序中,有時要用到很多的按鈕元件,沒個按鈕都要有一個監聽事件,為了讓代碼看起來干淨簡潔,並節省一些內存,我們可以用一個監聽器(Listener)來實現多個按鈕的onClick監聽下面是一個具有的例子:
  1. package com.android;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.net.Uri;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.widget.Button;
  8. public class IntentSelectActivity extends Activity implements View.OnClickListener{
  9. /** Called when the activity is first created. */
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.main);
  14. Button button1 = (Button)findViewById(R.id.btn1);
  15. Button button2 = (Button)findViewById(R.id.btn2);
  16. Button button3 = (Button)findViewById(R.id.btn3);
  17. button1.setOnClickListener(this);
  18. button1.setTag(1);
  19. button2.setOnClickListener(this);
  20. button2.setTag(2);
  21. button3.setOnClickListener(this);
  22. button3.setTag(3);
  23. }
  24. public void onClick(View v){
  25. int tag = (Integer) v.getTag();
  26. switch(tag){
  27. case 1:
  28. Intent music = new Intent(Intent.ACTION_GET_CONTENT);
  29. music.setType("audio/*");
  30. startActivity(Intent.createChooser(music, "Select music"));
  31. break;
  32. case 2:
  33. Intent dial = new Intent();
  34. dial.setAction("android.intent.action.CALL");
  35. dial.setData(Uri.parse("tel:13428720000"));
  36. startActivity(dial);
  37. break;
  38. case 3:
  39. Intent wallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
  40. startActivity(Intent.createChooser(wallpaper, "Select Wallpaper"));
  41. break;
  42. default :
  43. break;
  44. }
  45. }
  46. }

這段代碼用三個按鈕實現了三個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相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved