歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android簡單控件使用--計算BMI的例子

Android簡單控件使用--計算BMI的例子

日期:2017/3/1 11:09:08   编辑:Linux編程

在Android開發中,對於簡單的布局和控件使用,可以直接使用xml文件來做布局。下面用一個簡單的計算BMI的例子來說明如何使用Button,TextView這些簡單的控件。

布局文件如下: main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <AbsoluteLayout
  3. android:id="@+id/widget0"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. xmlns:android="http://schemas.android.com/apk/res/android" >
  7. <TextView
  8. android:id="@+id/showText"
  9. android:layout_width="wrap_content"
  10. android:layout_height="26px"
  11. android:text="計算你的標准體重!"
  12. android:textSize="25px"
  13. android:layout_x="65px"
  14. android:layout_y="21px">
  15. </TextView>
  16. <TextView
  17. android:id="@+id/text_Sex"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:text="性別:"
  21. android:layout_x="71px"
  22. android:layout_y="103px">
  23. </TextView>
  24. <TextView
  25. android:id="@+id/text_Height"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:text="身高:"
  29. android:layout_x="72px"
  30. android:layout_y="169px">
  31. </TextView>
  32. <RadioGroup
  33. android:id="@+id/radioGroup"
  34. android:layout_width="wrap_content"
  35. android:layout_height="37px"
  36. android:orientation="horizontal"
  37. android:layout_x="124px"
  38. android:layout_y="101px">
  39. <RadioButton
  40. android:id="@+id/Sex_Man"
  41. android:layout_width="wrap_content"
  42. android:layout_height="wrap_content"
  43. android:text="男">
  44. </RadioButton>
  45. <RadioButton
  46. android:id="@+id/Sex_Woman"
  47. android:layout_width="wrap_content"
  48. android:layout_height="wrap_content"
  49. android:text="女">
  50. </RadioButton>
  51. </RadioGroup>
  52. <EditText
  53. android:id="@+id/height_Edit"
  54. android:layout_width="123px"
  55. android:layout_height="wrap_content"
  56. android:text=""
  57. android:textSize="18sp"
  58. android:layout_x="124px"
  59. android:layout_y="160px">
  60. </EditText>
  61. <Button
  62. android:id="@+id/button_OK"
  63. android:layout_width="80px"
  64. android:layout_height="wrap_content"
  65. android:text="計算"
  66. android:layout_x="125px"
  67. android:layout_y="263px">
  68. </Button>
  69. </AbsoluteLayout>

在這個文件中,定義了3個TextView,2個RadioButton,用於選擇性別。一個EditText,用於輸入身高。

一個Button,用於計算BMI。

若要使用此布局,則只需要在Activity的onCreate()方法中調用:

  1. setContentView(R.layout.main);

每個控件都有很多內置的屬性,其中android:id屬性可以用來將Java代碼中的控件和此控件聯系起來。

Button btn = (Button)findViewById(R.id.button_OK);
Copyright © Linux教程網 All Rights Reserved