Android 常用控件讲解

来源:互联网 发布:mac 替换war文件 编辑:程序博客网 时间:2024/05/16 15:49

Android输入控件是一种用于人机交互的元件,Android为此提供了各种各样的输入控件,例如:按钮(Button),文本域(text fields),拖动条(seek bars),复选框(checkBos),缩放按钮(zoom buttons),开关按钮(togglebuttons),等等。

   为UI添加输入控件,只需要在对应的布局文件(XML Layout)添加对应的控件节点。如下,是一个包含编辑框和按钮的布局文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button android:id="@+id/button_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send"
        android:onClick="sendMessage" />
</LinearLayout>

   每个输控件都支持个特定的输事件,如当用户输文本或触摸个按钮,这样你就可以执行一个动作(处理事件)。

常规控制元件

下表列出了在App常用的输入元件,若要了解更为详细的信息,看参阅官方文档。

控件类型

描述

相关类

Button

按钮,可以被用户按下或点击,以执行个动作

Button

Text field

可编辑的文本区域,可以使用AutoCompleteTextView创建一个带有自动完成功能的编辑文本域

EditText,AutoCompleteTextView

Checkbox

复选框,个可以由用户切换的ON/OFF开关。当提供给用户组不互斥的可选项时,你应该使用复选框

CheckBox

Radio button

单选按钮,与CheckBox类型,只是一组里只能选择一个选项

RadioGroupRadioButton

Toggle button

切换按钮,带有亮度显示的 ON/OFF 按钮

ToggleButton

Spinner

下拉列表,让用户从一系列的值中选择一个值

Spinner

Pickers

选择器,一个通过使用向上/向下按钮或手势从系列值中选择个值的对话框。用DatePicker输日期(月,日,年)或用TimePicker输时间(时,分钟,上午/下午),这将被自动的格式化为用户区域的值(本地化)。

DatePicker,TimePicker

tips: 除了以上输入控件,Android还有很多未列出来的控件,可以浏览android.widget包去了解更多的控件信息。如果您的应用程序需要特定的输控件,你可以自定义该组件

Buttons

在Android里,Button可以有一下三种显示(纯文本,图片,或者文本+图片)。

根据给出来的三种形式,你可以在布局文件中通过以下三种方法创建一个Button。

纯文本组成,使用Button节点

1
2
3
4
5
6
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    ...
    />

由图片组成,使用ImageButton 节点(需要把相应的图片添加到drawable文件夹里)

1
2
3
4
5
<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/button_icon"
    ... />

文本+图片,使用Button节点和android:drawableLeft属性

1
2
3
4
5
6
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:drawableLeft="@drawable/button_icon"
    ... />

tips:还有drawableRight,drawableTop,drawableBottom,drawablePadding等等

如何响应Button的点击事件

响应Button的点击事件,大概可以分为以下两种方式:

 1、在java代码里添加事件监听器:

1
2
3
4
5
6
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // 响应按钮点击事件
    }
});


 2、在布局文件里定义Button的行为属性onClick,如下所示:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />

这样,在点击Button时,便会调用Activity里的sendMessage()方法处理事件。

在Activity里实现对应的事件处理方法sendMessage

1
2
3
4
/** 点击Button时调用*/
publicvoid sendMessage(View view){
    // 处理逻辑
}

   使用这种xml的定义方式,有以下几点是需要注意的:

1)在布局文件里onClick属性的值(onClick_event必须与Activity里方法名(onClick_event)一致(在这指sendMessage的一致)

2)方法onClick_event返回值必须为void,且为public方法

3onClick_event只能一个参数ViewView指事件源(Button

tips:在没有特别要求的情况下,可以选择其中一种来响应Button的点击事件。如果需要初始化Button控件或者在Fragment定义Button的响应方法,选择使用第一种方式。


定义Button的样式

不同版本的Android系统或者说由不同厂家生产的Android手机,其Button的默认显示样式都会有所不同。如果需要控制Button在各种版本显示一致的样式,可以选择定义App的主题样式。如:在Android4..0或者更高的版本中,可以定义Holo的主题样式——在manifest.xml<application>节点添加属性(低版本的系统需要添加对应支持包)

android:theme="@android:style/Theme.Holo"

类似的,可以通过在布局文件里<Button>节点添加属性android:background来定义Button的背景,其背景可以是一张图片或者是某种特定额颜色。

  android:background="@drawable/button_icon"

无框Button

偶尔,也许你会使用到无框按钮,可以通过在布局文件的<Button>节点添加borderlessButtonStyle来定义无框按钮


1
2
3
4
5
6
7
<Button
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
    style="?android:attr/borderlessButtonStyle" />

自定义Button的背景

   有时候为了炫酷的外观和用户体验的需要,需要重新定义Button的背景和形状(并不是简简单单地添加一张图片或者改变背景颜色)。那又是如何去美化Button默认的显示样式:

Demo1:使用位图来改变Button三种状态的样式(default—默认样式,pressed—被点击时样式,focused—获得焦点时的样式)

   第一步:选好或者制作好Button各种状态下的背景图片。需要注意的是,制作的图片要适应不同大小的Button,可以选择制成nine-patch位图。

   第二步:将做好的图片放到目录res/drawable/下,并为图片统一命名,如button_default.9.pngbutton_pressed.9.png,button_focused.9.png.

第三步:在res/drawable/下创建xml文件(button_custom.xml),如下:

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_default" />
</selector>

如此,便可为Button指定各种状态下的背景图片。

第四步:在布局文件里创建Button按钮,添加background属性(其值为@drawable/button_custom

1
2
3
4
5
6
7
<Button
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
    android:background="@drawable/button_custom"  />

注意:在button_custom.xml文件里,<item>有着顺序之分的,android会自上往下去搜索第一个满足条件的<item>,搜到就停止往下搜索。所以默认的显示图片需要放在最后一个。

Text Fields

   文本域组件中,EditText就是我们常用的一个组件。 EditText是一个非常重要的组件,可以说它是用户和App进行数据传输窗户,有了它就等于有了一扇和App传输的门,通过它用户可以把数据传给App,然后得到我们想要的数据。EditTextTextView的子类,所以TextView的方法和特性同样存在于EditText中,有兴趣的可以参阅官方文档了解TextView的特性。

为文本指定特定的软键盘类型

文本域里可以输入不同类型的信息,如数字、密码、email等等,在输入时,系统会根据输入类型来决定弹出哪一种虚拟键盘。那呀如何来确定文本域的输入类型呢??


在节点EditText里通过添加属性android:inputType来控制文本域的输入类型,如一个输入email的文本域,可以这样定义:

1
2
3
4
5
6
<EditText
    android:id="@+id/email_address"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/email_hint"
    android:inputType="textEmailAddress" />

对应弹出的键盘如下:

常用inputType有以下几种:

text”:常规文本键盘

textEmailAddress”:带有‘@’符号的常规文本键盘

textUrl”:带有‘/’的常规文本键盘

number”:数字键盘

phone”:拨号键盘


数字键盘

常规文本键盘

定制键盘的其他表现形式

通过属性android:inputTyp同样可以定制特定的键盘行为,如使首字母大写,使用拼写建议等等

属性android:inputType是通过按位组合得到值的,所以你可以一次性定制一个或多个值(使用“|”隔开)。

下面给出属性android:inputType常用的值:

"textCapSentences"常规文本键盘,句子首字母大写

"textCapWords"    常规文本键盘,所有单词首字母大写。(适合用来输入标题和人名)

"textAutoCorrect" 常规文本键盘,会纠正单词拼写错误

"textPassword"    数字键盘,以原点显示输入的数据

"textMultiLine"  常规文本键盘,允许用户输入多行文本


如下:定义了一个单词首字母大写,没有拼写建议的键盘

Demo

1
2
3
4
5
6
<EditText
    android:id="@+id/postal_address"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/postal_address_hint"
    android:inputType="textCapWords|textNoSuggestions" />

定制键盘指定键的Action

除了可以控制键盘的输入类型,我们一样可以去定制指定键(“回车键”)的Action。例如让“回车键”具有“发送”或者“搜索”的功能。

可以通过属性android:imeOptions来设置此Action,如下,使“回车键”具有“发送”的功能。

1
2
3
4
5
6
7
<EditText
    android:id="@+id/search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:inputType="text"
    android:imeOptions="actionSend" />

附:如果没有显式指定属性android:imeOptions的值,系统会自动往后搜索是否有可以获得焦点的组件,如果存在这样的组件,此时的“回车键”会显示为“Next”(actionNext);如果没有则显示为“Done”(actionDone)。


监听“回车键”的Action

如果通过android:imeOptions定制了“回车键”的Action(例如上文的“actionSend”),你需要使用TextView.OnEditorActionListener监听它的Action。监听器TextView.OnEditorActionListener.里有一个回调方法onEditorAction(),当中参数actionId用来识别哪一种Action,如IME_ACTION_SENDIME_ACTION_SEARCH.

Demo:监听是否按下了“Send”(actionSend)按钮。

1
2
3
4
5
6
7
8
9
10
11
12
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});


如果屏幕够大(如横屏的时候),你可以在EditText旁自定义一个按钮(用来实现某种逻辑),通过属性android:imeActionLabel来设置

1
2
3
4
5
6
7
<EditText
    android:id="@+id/launch_codes"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/enter_launch_codes"
    android:inputType="number"
    android:imeActionLabel="@string/launch" />

创建带有提示文的文本域

使用EditText的子类AutoCompleteTextView,可以创建带有提示文的文本域。根据提示文的来源不同(数据库或数组),AutoCompleteTextView提供了不同的适配器。

如下,演示如何使用ArrayAdapter(数组适配器)来创建AutoCompleteTextView

第一步:在布局文件里添加节点AutoCompleteTextView

1
2
3
4
<AutoCompleteTextView        xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/autocomplete_country"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

第二步:在strings.xml定义提示文数组,这里以输入国家名为列,给出各个国家名的提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_array">
        <item>Afghanistan</item>
        <item>Albania</item>
        <item>Algeria</item>
        <item>American Samoa</item>
        <item>Andorra</item>
        <item>Angola</item>
        <item>Anguilla</item>
        <item>Antarctica</item>
        ...
    <item>China</item>
    ...
    </string-array>
</resources>

第三步:在ActivityFragment里为AutoCompleteTextView设置适配器:

1
2
3
4
5
6
7
// 获得AutoCompleteTextView组件
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
// 从strings.xml获得国家名称的数组
String[] countries = getResources().getStringArray(R.array.countries_array);
// 创建适配器,并用setAdapter()为AutoCompleteTextView设置此适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
textView.setAdapter(adapter);

在这里,ArrayAdapter绑定了国家名称的数组countries,并以TextView的形式和simple_list_item_1的布局显示。布局simple_list_item_1Android系统为列表信息的显示提供的一种标准外观。

效果如图:


附:在这里只是为演示功能的使用,所有并没有设置所有的国家名称提示文,(可根据App的实际需要来设置提示文)

Checkboxes(复选框)

CheckBos(复选框)的主要功能就是完成复选框额操作,在用户输入信息时,可以一次性选择多个内容。例如,用户在选择个人兴趣爱好时,或者用户在设置系统的功能时,这样选项一定会存在一个或多个,则此时可以直接使用CheckBox完成此功能。


监听CheckBox的点击事件

往布局文件里的<CheckBox>节点添加属性android:onClick,其值为调用的方法名(与上文Button用法类似)。

Demo

在布局文件定义两个CheckBox

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <CheckBox android:id="@+id/checkbox_meat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/meat"
        android:onClick="onCheckboxClicked"/>
    <CheckBox android:id="@+id/checkbox_cheese"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cheese"
        android:onClick="onCheckboxClicked"/>
</LinearLayout>

Activity里实现对应的事件处理方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void onCheckboxClicked(View view) {
    // 获得checkBox的选中状态(选中或不选)
    boolean checked = ((CheckBox) view).isChecked();
                                                                                                                                                                 
    switch(view.getId()) {//通过Id获得改变了状态的CheckBox
        case R.id.checkbox_meat:
            if (checked)
                // 选中状态下的逻辑
            else
                // 没有选中状态下的逻辑
            break;
        case R.id.checkbox_cheese:
            if (checked)
                //选中状态下的逻辑
            else
                //没有选中状态下的逻辑
            break;
        // ...
    }
}

使用这种xml设置响应方式的定义方式,有以下几点是需要注意的:

1)在布局文件里onClick属性的值(onClick_event)必须与Activity里方法名(onClick_event)一致(在这指onCheckboxClicked的一致)

2)方法onClick_event返回值必须为void,且为public方法

3onClick_event只能一个参数ViewView指事件源(CheckBox


同样地,可以在java代码里添加监听器(CompoundButton.OnCheckedChangeListener):

1
2
3
4
5
6
7
8
9
10
11
12
meat = (CheckBox) findViewById(R.id.checkbox_meat);
// 给CheckBox设置事件监听
meat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 选中状态下的逻辑
                else {
                    // 没有选中状态下的逻辑
                }
            }
        });

      

tips:可以用setcheckedboolean)或 toggle()方法来设置checkbox的选中状态。

Radio Buttons


RadioButton(单选按钮)提供了一种多选一的操作模式(添加到RadioGroup里),例如从性别“男”或“女”中选择一个。

Demo

在布局文件里定义RadioGroupRadioButton

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton android:id="@+id/radio_pirates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/pirates"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton android:id="@+id/radio_ninjas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ninjas"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>

附:RadioGroupLinearLayout的一个子类,其orientation默认为vertical

Activity里实现对应的事件处理方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void onRadioButtonClicked(View view) {
    // 获得RadioButton的选中状态(选还是没选)
    boolean checked = ((RadioButton) view).isChecked();
                                                                                                                           
    switch(view.getId()) {//通过Id获得改变了状态的CheckBox
        case R.id.radio_pirates:
            if (checked)
                // 选中了R.id.radio_pirates
            break;
        case R.id.radio_ninjas:
            if (checked)
                // 选中了R.id.radio_ninjas
            break;
    }
}

使用这种xml设置响应方式的定义方式,有以下几点是需要注意的:

1)在布局文件里onClick属性的值(onClick_event)必须与Activity里方法名(onClick_event)一致(在这指onRadioButtonClicked的一致)

2)方法onClick_event返回值必须为void,且为public方法

3onClick_event只能一个参数ViewView指事件源(RadioButton

同样地,可以在java代码里添加监听器(RadioGroup.OnCheckedChangeListener,注意这里的监听器和上文提到的CompoundButton.OnCheckedChangeListener是不一样的),实现方法与上文类似,在此需要为RadioGroup添加一个IdradioGroup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 通过findViewById获得RadioGroup对象
        raGroup = (RadioGroup) findViewById(R.id.radioGroup);
        // 添加事件监听器
        raGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_pirates) {
                    // 选中R.id. radio_pirates的逻辑
                else if (checkedId == R.id.radio_ninjas) {
                    // 选中R.id.radio_ninjas的逻辑
                else {
                    // 其他逻辑
                }
            }
        });


Toggle Buttons

ToggleButton(开关按钮)是让用户(对某功能)在on/off下选择,并可以不同的状态on/off设置不同的显示文本。在Android 4.0API 14)之后,提供了另外一种表现形式Switches,如下所示:

      ToggleButton  Switch 都是CompoundButton的子类,所以可以选择类似的方式来使用ToggleButton Switch

设置ToggleButtons的响应方式

在布局文件<ToggleButton><Switch>节点添加属性android:onClick .

1
2
3
4
5
6
7
<ToggleButton
    android:id="@+id/togglebutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="on"
    android:textOff="off"
    android:onClick="onToggleClicked"/>

附:属性textOntextOff用来设置ToggleButton on/off状态下显示的文本,在Android4.0或更高的版本,可以使用<Switch>来代替<ToggleButton>

Activity里实现对应的事件处理方法:

1
2
3
4
5
6
7
8
9
10
public void onToggleClicked (View view) {
    // 判断是否处在“on”状态下
    boolean on = ((ToggleButton) view).isChecked();
                                                                                           
    if (on) {
        // on 状态下的逻辑
    else {
        // off 状态下的逻辑
    }
}

使用这种xml设置响应方式的定义方式,有以下几点是需要注意的:

1)在布局文件里onClick属性的值(onClick_event)必须与Activity里方法名(onClick_event)一致(在这指onToggleClicked的一致)

2)方法onClick_event返回值必须为void,且为public方法

3onClick_event只能一个参数ViewView指事件源(ToggleButton


同样地,可以在java代码里添加监听器(CompoundButton.OnCheckedChangeListener),实现方法与上文类似

1
2
3
4
5
6
7
8
9
10
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // on 状态下的逻辑
        else {
            // off状态下的逻辑
        }
    }
});

Spinners

Spinner(下拉列表),以列表的形式供用户去选择,与CheckBox(复选框)或RadioButton(单选按钮)相比,Spinner可以节省手机的屏幕空间。

Demo:

在布局文件里定义一个下拉列表:

1
2
3
4
<Spinner
    android:id="@+id/planets_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

在布局文件定义了<Spinner>节点之后,接着需要设置其显示的列表项,根据列表项数据来源的不同,可以创建不同的适配器(类似于AutoCompleteTextView的实现)。比较常用的有ArrayAdapter适配器,下面演示一下其用法(以八大恒星为例)

第一步:在strings.xml添加数组plantts_array

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-arrayname="planets_array">
        <item>水星</item>
        <item>金星</item>
        <item>地球</item>
        <item>火星</item>
        <item>木星</item>
        <item>土星</item>
        <item>天王星</item>
        <item>海王星</item>
    </string-array>
</resources>

第二步:在Activity Fragment里设置Spinner的适配器:

1
2
3
4
5
6
7
Spinner spinner =(Spinner) findViewById(R.id.spinner);
// 使用默认的下拉列表布局和数组plants_array来创建数组适配器ArrayAdapter
ArrayAdapter<CharSequence> adapter =ArrayAdapter.createFromResource(this,R.array.planets_array, android.R.layout.simple_spinner_item);
// 指定所弹出的下拉列表的布局方式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// 为spinner设置适配器
spinner.setAdapter(adapter);

附:simple_spinner_item  simple_spinner_dropdown_item都是系统为下拉列表提供的一种布局方式。


有着另外一种更加简单配置方法,如下:

第一步与上面一样,在strings.xml添加数组planets_array

第二步:在<Spinner>节点添加属性android:entries,其值指向planets_array数组

1
2
3
4
5
<Spinner
        android:id="@+id/planets_spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:entries="@array/planets_array"/>

其实现效果是一样的。

响应用户的选择

监听用户的选择,需要实现监听器AdapterView.OnItemSelectedListener内的方法onItemSelected()onNothingSelected(),如下给出了实现此监听器的Activity

1
2
3
4
5
6
7
8
9
10
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
    ...
                                                             
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    //可以使用方法parent.getItemAtPosition(pos)获得用户选择的选项
    }
    public void onNothingSelected(AdapterView<?> parent) {
        //用户没有选取任何选项时触发此方法
    }
}

接着通过setOnItemSelectedListener()spinner设置监听器,代码如下:

1
2
Spinner spinner =(Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);

附:同样也可以使用内部类的方式为spinner设置监听器,实现方式与前文提到的组件类似。

Pickers(选择器)

      android 为用户提供里一个选择时间/日期的现成对话框,如图。

      Picker(选择器)自动调整为当地的语言环境,可以确保你得到一个遵循一定格式的时间(或者日期)。

推荐使用DialogFragment来管理时间和日期选择器,因为DialogFragment会为你管理这些选择器的生命周期,且允许在不同的布局配置里显示这些选择器(如在小屏幕的手机上显示为基本的对话框,在大屏幕上则内嵌如到布局里去)。

附:从Android3.0开始才开始支持DialogFragment,如果需要运行在低版本的手机上,可以添加对应的支持包。


创建时间选择器Time Picker

要使用DialogFragment来显示TimePickerDialog,需要做到以下三点:

 1、创建一个片段类继承TimePickerFragment继承DialogFragment

  2、在onCreateDialog()里返回TimePickerDialog的对象

      3、实现TimePickerDialog.OnTimeSetListener接口

如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //用当前时间作为picker的默认时间
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        // 创建TimePickerDialog对象并返回该对象
        return new TimePickerDialog(getActivity(), this, hour, minute,DateFormat.is24HourFormat(getActivity()));
    }
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        //当用户设置好(点击“Set”按钮)之后的逻辑
    }
}

附:可参考API文档了解各个参数的意义

设计好TimePickerFragment之后,需要做的就是,在Activity创建TimePickerFragment的对象并调用其show()方法即可

如下:定义了一个按钮,点击后便后弹出TimePickerDialog

1
2
3
4
5
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_time"
    android:onClick="showTimePickerDialog" />

Button对应的事件处理方法如下:

1
2
3
4
public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}


创建日期选择器(Date Picker

其方法与时间选择器类似。

要使用DialogFragment来显示DatePickerDialog,需要做到以下三点:

      1、创建一个片段类继承DatePickerFragment继承DialogFragment

      2、在onCreateDialog()里返回DatePickerDialog的对象

      3、实现DatePickerDialog.OnDateSetListener接口

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        //使用当前日期作为date picker 的默认显示日期
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        // 创建 DatePickerDialog 对象并返回给对象
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }
    public void onDateSet(DatePicker view, int year, int month, int day) {
        //当用户设置好(点击“Set”按钮)之后的逻辑
    }
}

接着定义一个Button

1
2
3
4
5
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_date"
    android:onClick="showDatePickerDialog" />

最后在Activity里实现对应的事件处理方法

1
2
3
4
public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}


本文出自 “静心天涯” 博客,请务必保留此出处http://peiquan.blog.51cto.com/7518552/1283065

0 0
原创粉丝点击