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

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

<RelativeLayoutandroid:id="@+id/relative"

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

android:gravity="center">

<Buttonandroid:id="@+id/button"

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

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

<TextViewandroid:layout_height="wrap_content"

android:layout_width="fill_parent"

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

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

</RelativeLayout>

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

publicclassCustomButtonextendsButton

{

PublicCustomButton(Contextcontext,AttributeSetattrs)

{

super.(context,attrs);

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

}

ProtectedvoidonDraw(Canvascanvas)

{

//图片顶部居中显示

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

inty=0;

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

//让文字在底部显示

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

super.onDraw(canvas);

}

}

更多相关文章

  1. android 添加文件打开方式,找了很久终于找到了,收藏起来吧
  2. Android TextView文字链接4中方法
  3. TextView 文字描边
  4. 演化理解 Android 异步加载图片
  5. Android布局的一些属性和开关、创建log图片
  6. Android WebView实现选择本地图片拍照功能
  7. Android--布局方式(LinearLayout)学习
  8. Android Studio App设置TextView文字内容大小颜色
  9. Android中的几种网络请求方式详解

随机推荐

  1. 第一个Android实例——计算器 编辑
  2. 2016Android开发技术篇
  3. Android Activity生命周期详解
  4. 【转】Android通过共享用户ID来实现多Act
  5. Android widget之ListView
  6. Android--spinner选择框,AutoCompleteText
  7. 【Android问题】Android导入一个工程时提
  8. logcat 总是报: W/StaticLayout: maxLineH
  9. Android Studio 打包apk,自动追加版本号和
  10. Android(安卓)Notification