Android 控件开发之ImageButton

来源:互联网 发布:matlab遗传算法知乎 编辑:程序博客网 时间:2024/05/18 02:18
/**
 * 除了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源码:
  

[cpp] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.    android:orientation="vertical"  
  4.    android:layout_width="fill_parent"  
  5.    android:layout_height="fill_parent">  
  6. lt;TextView    
  7.    android:layout_width="fill_parent"   
  8.    android:layout_height="wrap_content"   
  9.    android:text="这是一个带图片的按钮.ImageButton"/>  
  10.      
  11. lt;ImageButton   
  12.    android:id="@+id/imageButton"  
  13.    android:layout_width="wrap_content"  
  14.    android:layout_height="wrap_content"/>  
  15.   
  16. lt;/LinearLayout>  


本程序java源码

[cpp] view plaincopy
  1. package com.sx.ImageButton;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.widget.Button;  
  7. import android.widget.ImageButton;  
  8.   
  9.   
  10. public class ImageButtonActivity extends Activity  
  11. {  
  12.     /** Called when the activity is first created. */  
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState)   
  15.     {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.           
  19.         final ImageButton imageButton = (ImageButton)findViewById(R.id.imageButton);  
  20.           
  21.         imageButton.setImageDrawable((getResources().getDrawable(R.drawable.icon)));  
  22.           
  23.         imageButton.setOnClickListener(new Button.OnClickListener()  
  24.         {  
  25.         @Override  
  26.         public void onClick(View arg0)   
  27.         {  
  28.             //ImageButton事件响应  
  29.         }  
  30.            
  31.         });  
  32.     }  
  33. }  
0 0
原创粉丝点击