Android 控件開發之ImageButton

/**
 * 除了Android系統自帶的Button按鈕一萬,還提供了帶圖標的按鈕ImageButton 
 * 要製作帶圖標的按鈕,首先要在佈局文件中定義ImageButton,然後通過setImageDrawable
 * 方法來設置要顯示的圖標。

注意:
我們可以在佈局文件中就直接設置按鈕的圖標,如
android:src="@drawable/icon1"

我們也可以在程序中設置自定義圖標
imgbtn3.setImageDrawable(getResources().getDrawable(R.drawable.icon2));

我們還可以使用系統自帶的圖標
imgbtn4.setImageDrawable(getResources().getDrawable(android.R.drawable.sym_call_incoming));

       設置完按鈕的圖標後,需要爲按鈕設置監聽setOnClickListener,以此捕獲事件並處理

*/

   ImageButton 效果圖:



本程序main.xml源碼:
  

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="這是一個帶圖片的按鈕.ImageButton"/>
    
<ImageButton 
    android:id="@+id/imageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</LinearLayout>





本程序java源碼

package com.sx.ImageButton;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;


public class ImageButtonActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final ImageButton imageButton = (ImageButton)findViewById(R.id.imageButton);
        
        imageButton.setImageDrawable((getResources().getDrawable(R.drawable.icon)));
        
        imageButton.setOnClickListener(new Button.OnClickListener()
        {
		@Override
		public void onClick(View arg0) 
		{
			//ImageButton事件響應
		}
         
        });
    }
}



   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章