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


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

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

  1. 准备一张NinePatch资源图片(button.9.png),具体方法参考();
  2. 将button.9.png拖曳(drag)到android工程的/res/drawable-mdpi目录下。
  3. 修改main.XML文件:
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     android:layout_width="fill_parent"  
    4.     android:layout_height="fill_parent"  
    5.     android:orientation="vertical" >  
    6.   
    7.     <TextView  
    8.         android:layout_width="fill_parent"  
    9.         android:layout_height="wrap_content"  
    10.         android:text="@string/hello" />  
    11.   
    12.     <Button  
    13.         android:id="@+id/btn1"  
    14.         android:layout_width="wrap_content"  
    15.         android:layout_height="wrap_content"  
    16.         android:background="@drawable/button"  
    17.         android:text="music"  
    18.         android:textSize="12sp" />  
    19.   
    20.     <Button  
    21.         android:id="@+id/btn2"  
    22.         android:layout_width="wrap_content"  
    23.         android:layout_height="wrap_content"  
    24.         android:background="@drawable/button"  
    25.         android:text="dialer"  
    26.         android:textSize="24sp" />  
    27.   
    28.     <Button  
    29.         android:id="@+id/btn3"  
    30.         android:layout_width="wrap_content"  
    31.         android:layout_height="wrap_content"  
    32.         android:background="@drawable/button"  
    33.         android:text="wallpaper"  
    34.         android:textSize="48sp" />  
    35.   
    36. </LinearLayout>  

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

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

更多Android相关信息见Android 专题页面 http://www.bkjia.com/topicnews.aspx?tid=11

相关内容