zoukankan      html  css  js  c++  java
  • android带有文字的图片按钮的两种实现方式

    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);

    }

     

  • 相关阅读:
    Java设计模式-装饰器模式
    【c++内存分布系列】单独一个类
    【转】LCS
    快速排序
    冒泡排序
    选择排序
    多线程读取全局变量
    【转】一致性hash算法(consistent hashing)
    【转】五笔的字典序编码与解码
    给定一个函数rand()能产生0到n-1之间的等概率随机数,问如何产生0到m-1之间等概率的随机数?
  • 原文地址:https://www.cnblogs.com/wangmars/p/3261952.html
Copyright © 2011-2022 走看看