閱讀908 返回首頁    go 京東網上商城


Android中利用LinearLayout繼承實現ImageButton

 

原理:通過繼承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. }  
import android.widget.TextView; public class ImageButton1 extends LinearLayout{ private ImageView mImage; private TextView mText; public ImageButton1(Context context, AttributeSet attrs) { super(context,attrs); mImage = new ImageView(context,attrs); mImage.setPadding(0,0,0,0); mText = new TextView(context,attrs); //mText.setGravity(android.view.Gravity.CENTER_HORIZONTAL); // mText.setGravity(android.view.Gravity.CENTER_VERTICAL); mText.setPadding(0,0,0,0); setClickable(true); setFocusable(true); setBackgroundResource(android.R.drawable.btn_default); setOrientation(LinearLayout.VERTICAL); addView(mImage); addView(mText); }}

 

調用自己編寫的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.     />   
<com.test.b.ImageButton1 android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" android:text="MOAR" android:textColor="#ff000000" />

注意調用ImageButton1時,要用全名:com.test.b.ImageButton1 

 

 

效果:button中上圖下文字

 

 

ImageButton

 

最後更新:2017-04-02 06:51:46

  上一篇:go 7.1.2 DatePicker結合案例詳解
  下一篇:go 使用Apache HttpClient實現多線程下載的小例子