歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android游戲開發系統控件-ImageButton

Android游戲開發系統控件-ImageButton

日期:2017/3/1 10:22:56   编辑:Linux編程

Android游戲開發系統控件-ImageButton

ImageButton與Button類似,區別在於ImageButton可以自定義一張圖片作為一個按鈕;

也正因為使用圖片代替了按鈕,所以ImageButton按下和抬起的樣式效果需要自定義。

下面為學習ImageButton做的的實例:

創建ImageButton項目

模擬器運行效果截圖:

按下按鈕:

抬起按鈕:

項目源碼:

main.xml修改如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <ImageButton
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:id="@+id/imageBtn"
  10. android:background="@drawable/nopress"/>
  11. </LinearLayout>

ImageButtonActivity.java代碼修改如下:

  1. package com.ImageButton;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.MotionEvent;
  5. import android.view.View;
  6. import android.view.View.OnTouchListener;
  7. import android.widget.ImageButton;
  8. public class ImageButtonActivity extends Activity {
  9. private ImageButton Ibtn;
  10. /** Called when the activity is first created. */
  11. @Override
  12. public void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. Ibtn = (ImageButton)findViewById(R.id.imageBtn);
  16. //為圖片按鈕添加觸屏監聽
  17. Ibtn.setOnTouchListener(new OnTouchListener(){
  18. public boolean onTouch(View v,MotionEvent event){
  19. //當前用戶為按下
  20. if(event.getAction()==MotionEvent.ACTION_DOWN){
  21. //設置圖片按鈕背景圖
  22. Ibtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.press));
  23. //用戶當前為抬起
  24. }else if(event.getAction()==MotionEvent.ACTION_UP){
  25. Ibtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.nopress));
  26. }
  27. return false;
  28. }
  29. });
  30. }
  31. }

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved