android 自定义按钮控件

来源:互联网 发布:网络用语gm是什么意思 编辑:程序博客网 时间:2024/05/29 08:34

创建自定义控件的3种主要实现方式:
1)继承已有的控件来实现自定义控件: 主要是当要实现的控件和已有的控件在很多方面比较类似, 通过对已有控件的扩展来满足要求。
2)通过继承一个布局文件实现自定义控件,一般来说做组合控件时可以通过这个方式来实现。
    注意此时不用onDraw方法,在构造广告中通过inflater加载自定义控件的布局文件,再addView(view),自定义控件的图形界面就加载进来了。
3)通过继承view类来实现自定义控件,使用GDI绘制出组件界面,一般无法通过上述两种方式来实现时用该方式。

还是按照国际惯例:


自定义的view:

public class ImageTextButton2 extends Button {Bitmap bitmaps;public ImageTextButton2(Context context) {super(context, null);}public ImageTextButton2(Context context, AttributeSet attributeSet) {super(context, attributeSet);this.setClickable(true);bitmaps = BitmapFactory.decodeResource(getResources(), R.drawable.icon);}protected void onDraw(Canvas canvas) {int x = 0;//int y = (getMeasuredHeight() - bitmaps.getHeight()) / 2;// y坐标canvas.drawBitmap(bitmaps, x, y, null);//图片 //Bitmap:图片对象,left:偏移左边的位置,top: 偏移顶部的位置canvas.translate(this.getMeasuredWidth() / 3 - (int) this.getTextSize(), 0);//文字super.onDraw(canvas);}}


布局页面:

<?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="@string/hello"    />  <com.test.ImageTextButton2      android:layout_gravity="center"   android:id="@+id/bt2"   android:layout_marginTop="10dp"   android:text="@string/hello"   android:textSize="15sp"   android:textColor="#000000"   android:layout_width="100dp"   android:layout_height="70dp"   android:background="@drawable/button_bg"  /></LinearLayout>


注意:布局页面中的宽度大小变化,this.getMeasuredWidth() / 3的比例也要跟着变。因为这是按照百分比来计算宽度的。不过有点我不懂,在xml 中报在view类中的bitmaps.getHeight()的错误,为了小弟给大家更好的资料分享,希望懂的大神可以回复评论怎么改。

想看例子的看客们:点击下载



0 0
原创粉丝点击