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);
}
}
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);
}
}
相关文章推荐
- Android 蓝牙打印小票与WiFi打印小票两种打印方式的实现(带有图片和二维码)
- Android实现图片的高斯模糊(两种方式)
- 分享实现Android图片选择的两种方式
- 图片设置[置顶] Android之Gallery和GridView两种方式与ImageSwitcher实现带预览的和幻灯片方式的两种图片浏览器
- Android实现圆形图片的两种方式
- Android中实现虚线边框包裹文字的两种方式
- Android ListView常用用法 (实现文字图片和按钮)
- Android实现图片的高斯模糊(两种方式)
- 实现、文件-Android中的ListView实现图片文字和按钮-by小雨
- ListView、RecyclerView 两种方式实现聊天界面支持文字、表情、图片和语音信息,支持下拉加载更多
- android实现自定义图片+文字按钮
- android实现图片闪烁动画效果的两种实现方式(实用性高)
- android中EditText点击右边叉叉按钮(或图片)清除输入框内的文字的实现
- CSS和JQ两种方式实现图片层上显示文字
- Android实战简易教程<四十九>(两种方式实现网络图片异步加载)
- android两种方式实现圆形图片
- Android中将方形图片截取成圆形的两种实现方式
- Android 图片旋转动画两种实现方式
- android两种方式中自己画一个圆,实现单点触控时拖动图片,跟着拖动点走,并且可以放大或缩小
- Android中的ListView实现图片文字和按钮