原理:通过继承Linearlayout,摆放自己所需的imageview和textview,形成ImageButton
直接上源码:
view plaincopy to clipboardprint?
01.import android.widget.TextView;
02.
03.public class ImageButton1 extends LinearLayout
04.{
05. private ImageView mImage;
06. private TextView mText;
07.
08. public ImageButton1(Context context, AttributeSet attrs)
09. {
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
view plaincopy to clipboardprint?
01.
02. android:id="@+id/imbtn01"
03. android:layout_width="wrap_content"
04. android:layout_height="wrap_content"
05. android:src="@drawable/icon"
06. android:text="MOAR"
07. android:textColor="#ff000000"
08. />
android:id="@+id/imbtn01"
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中上图下文字