您的位置:首页 > 移动开发 > Android开发

android带有文字的图片按钮的两种实现方式

2013-08-16 13:38 423 查看
android带有文字的图片按钮的两种实现方式

1). TextView对Button用相对布局,这要要求按钮的背景图片要留下空白位置给文字。这种方式开发比较简单,适合做一些风格一致的Button。

<RelativeLayout android:id="@+id/relative"

android:layout_width="wrap_content" android:layout_height=" wrap_content "

android:gravity="center">

<Button android:id="@+id/button"

android:layout_width="fill_parent" android:layout_height="fill_parent"

android:background="@drawable/button_bg"/>

<TextView android:layout_height="wrap_content"

android:layout_width="fill_parent"

android:text=" 图片上的文字"

android:layout_alignParentBottom="true" android:gravity="center" />

</RelativeLayout>

2).自定义控件继承Button, 重写onDraw(Canvas canvas)把图片绘制上去,字体位置可以改变,不依赖已有的图片。这种方式比较灵活,可以实现复杂的需求。

public class CustomButton extends Button

{

Public CustomButton (Context context , AttributeSet attrs)

{

super.( context, attrs);

bitmap = BitmapFactory.decodeResource(getResources(), resourceId);

}

Protected void onDraw(Canvas canvas)

{

//图片顶部居中显示

int x=(this.getMeasuredWidth()-bitmap.getWidth())>>1;

int y=0;

canvas.drawBitmap(bitmap,x,y,null);

//让文字在底部显示

canvas.translate(0, (this.getMeasuredHeight()>>1)-(int)this.getTextSize());

super.onDraw(canvas);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: