歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android使用NinePatch圖片實現大小可變的Button

Android使用NinePatch圖片實現大小可變的Button

日期:2017/3/1 10:21:10   编辑:Linux編程

在Android的一些應用程序中,有時要用到大小可以延展的圖片做背景,實現的方法是使用NinePatch。

下面是一個用NinePatch圖片給Button做背景的例子,實現一個可以隨文字大小而改變的圖片Button:

  1. 准備一張NinePatch資源圖片(button.9.png),具體方法參考(http://www.linuxidc.com/Linux/2012-05/61515.htm);
  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. <TextView
    7. android:layout_width="fill_parent"
    8. android:layout_height="wrap_content"
    9. android:text="@string/hello" />
    10. <Button
    11. android:id="@+id/btn1"
    12. android:layout_width="wrap_content"
    13. android:layout_height="wrap_content"
    14. android:background="@drawable/button"
    15. android:text="music"
    16. android:textSize="12sp" />
    17. <Button
    18. android:id="@+id/btn2"
    19. android:layout_width="wrap_content"
    20. android:layout_height="wrap_content"
    21. android:background="@drawable/button"
    22. android:text="dialer"
    23. android:textSize="24sp" />
    24. <Button
    25. android:id="@+id/btn3"
    26. android:layout_width="wrap_content"
    27. android:layout_height="wrap_content"
    28. android:background="@drawable/button"
    29. android:text="wallpaper"
    30. android:textSize="48sp" />
    31. </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.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved