常用控件

  控件是对数据和方法的封装。控件可以有自己的属性和方法。属性是控件数据的简单访问者。方法则是控件的一些简单而可见的功能。所有控件都是继承View类

介绍android原生提供几种常用的控件button/imagebutton、checkbox/radiobutton、progressbar/seekbar、tabSpec/tabHost、ListView、Dialog,主要为了掌握控件使用的一般规律。


1、button 按钮

  Button是各种UI中最常用的控件之一,用户可以通过触摸它来触发一系列事件,要知道一个没有点击事件的Button是没有任何意义的,

因为使用者的固定思维是见到它就想去点!

  布局文件里button的xml声明:

1 <Button 
2             android:layout_width="fill_parent"
3             android:layout_height="wrap_content"
4             android:text="@string/btn_ok"
5             android:id="@+id/btn_ok"
6             />

  android:layout_width="wrap_content" --自适应,据自己的值占据控件来决定大小
  android:layout_height="fill_parent" --充满父控件,自动放大到与父控件一样的大小

  其中每个组件的layout_width和layout_height属性是必须的

  一般也可以是具体的大小,即:数字+单位,如android:layout_height ="30px",由于移动设备屏幕尺寸太多了,不推荐使用强制设定大小,通用性不好。

  @+表示声明,新增一个id,会自动在R.java文件里创建。如 android:,引用string.xml的名为hello_world的值

   xml自定义值可以这样:

1 <string name="hello_world">Hello world!</string>

  有些人会问直接 android:text="Hello world!"不是更方便,为什么还要引用xml文件?其实android这样设计为了国际化和编写弹性的应用程序,

xml解析时会讲到(了解更多XML:android学习日记23--Android XML解析),不多做解释了。布局组件等一般设置格式:

 

<布局/组件名称
android:属性="属性类型"
……
/>

 

如底下的xml:

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity" >
10     <!-- 线性布局  --> 
11      <LinearLayout
12      android:layout_width="fill_parent"
13      android:layout_height="wrap_content"
14      android:orientation="horizontal">
15     
16         <TextView
17             android:layout_width="wrap_content"
18             android:layout_height="wrap_content"
19             android:text="@string/hello_world" 
20             android:id="@+id/tv"
21             />
22     
23     
24         <Button 
25             android:layout_width="wrap_content"
26             android:layout_height="wrap_content"
27             android:text="@string/btn_ok"
28             android:id="@+id/btn_ok"
29             />
30     
31         <!-- wrap_content:自适应 --> 
32         <Button 
33             android:layout_width="wrap_content" 
34             android:layout_height="wrap_content"
35             android:text="@string/btn_cancle"
36             android:id="@+id/btn_cancle"
37             />
38         
39         <ImageButton 
40             android:layout_width="wrap_content" 
41             android:layout_height="wrap_content"
42             android:background="@drawable/blank"
43             android:id="@+id/btn_img"
44             />
45 
46     </LinearLayout>
47     
48 </RelativeLayout>
View Code

相关文章: