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

    }

     

  • 相关阅读:
    对学生排序 Exercise07_17
    消除重复 Exercise07_15
    计算gcd Exercise07_14
    随机数选择器 Exercise07_13
    dom4j 学习总结
    jQuery学习总结(二)
    jQuery学习总结(一)
    SQL中Where与Having的区别
    html + css (1)
    struts2+json
  • 原文地址:https://www.cnblogs.com/wangmars/p/3261952.html
Copyright © 2020-2023  润新知