Android使用NinePatch图片实现大小可变的Button

在Android的一些应用程序中,有时要用到大小可以延展的图片做背景,实现的方法是使用NinePatch。

下面是一个用NinePatch图片给Button做背景的例子,实现一个可以随文字大小而改变的图片Button:

  1. 准备一张NinePatch资源图片(button.9.png),具体方法参考(http://blog.csdn.net/imyang2007/article/details/7615363);
  2. 将button.9.png拖曳(drag)到android工程的/res/drawable-mdpi目录下。
  3. 修改main.XML文件:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello" />
    
        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button"
            android:text="music"
            android:textSize="12sp" />
    
        <Button
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button"
            android:text="dialer"
            android:textSize="24sp" />
    
        <Button
            android:id="@+id/btn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button"
            android:text="wallpaper"
            android:textSize="48sp" />
    
    </LinearLayout>

    这里的做法是,在UI上摆放Button元件,并设定Button上的文字及大小。通过「android:background」属性设定,将Button的背景设定为「@drawable/button」,即「drawable资源(drawable-mdpi/目录)里的button图片」,Android框架会去找到button.9.png档案。因为button.9.png是一张NinePatch图片,因此会随着Button上的文字大小延展。

此时所有工作已完成,不需要改写任何代码,程序运行效果如下:

转载请注明出处:http://blog.csdn.net/imyang2007/article/details/7615558



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值