现在的位置: 首页 > 综合 > 正文

Android中利用LinearLayout继承实现ImageButton

2014年01月16日 ⁄ 综合 ⁄ 共 2001字 ⁄ 字号 评论关闭
 

原理:通过继承Linearlayout,摆放自己所需的imageview和textview,形成ImageButton

直接上源码:

  

  1. import android.widget.TextView;  
  2.    
  3. public class ImageButton1 extends LinearLayout  
  4. {  
  5.   private ImageView mImage;  
  6.   private TextView mText;  
  7.    
  8.   public ImageButton1(Context context, AttributeSet attrs)  
  9.   {  
  10.     super(context,attrs);  
  11.    
  12.     mImage = new ImageView(context,attrs);  
  13.     mImage.setPadding(0,0,0,0);  
  14.     mText = new TextView(context,attrs);  
  15.     //mText.setGravity(android.view.Gravity.CENTER_HORIZONTAL);   
  16.   //  mText.setGravity(android.view.Gravity.CENTER_VERTICAL);   
  17.     mText.setPadding(0,0,0,0);  
  18.      
  19.       
  20.     setClickable(true);  
  21.     setFocusable(true);  
  22.     setBackgroundResource(android.R.drawable.btn_default);  
  23.     setOrientation(LinearLayout.VERTICAL);  
  24.     addView(mImage);  
  25.     addView(mText);  
  26.   }  
  27. }  

 

调用自己编写的ImageButton1

 

  1. <com.test.b.ImageButton1     
  2.     android:id="@+id/imbtn01"  
  3.     android:layout_width="wrap_content"      
  4.     android:layout_height="wrap_content"      
  5.     android:src="@drawable/icon"    
  6.     android:text="MOAR"    
  7.     android:textColor="#ff000000"    
  8.     />   

注意调用ImageButton1时,要用全名:com.test.b.ImageButton1 

 

 

效果:button中上图下文字

 

 

ImageButton

 

抱歉!评论已关闭.