今天是第一次写技术博客,Android我也是刚刚接触,希望和正在学习Android的一起进步,如果哪有写错的地方希望大家给予指正。谢谢
Spinner相当HTML的下拉列表,下面我们实现一个在注册中选择血型的例子:
首先在res/values/string.xml写一个string的集合,string.xml这个文件主要是放一些文字信息的
比如验证内容,要显示的文字等,定义这个集合的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, registActivity!</string>
<string name="app_name">注册</string>
<string name="xuexing">血 型:</string>
<string-array name="xuexings">
<item>A</item>
<item>B</item>
<item>O</item>
<item>AB</item>
</string-array>
</resources>
然后是在reg/layout/main.xml中写如下内容:
<Spinner
android:id="@+id/s1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/xuexing"
>
</Spinner>
打开你的registActivity.java文件,代码如下:
package com.regestcoo;
|
import android.app.Activity; |
|
import android.os.Bundle; |
|
import android.view.View; |
|
import android.widget.AdapterView; |
|
import android.widget.AdapterView.OnItemSelectedListener; |
|
import android.widget.ArrayAdapter; |
|
import android.widget.Spinner; |
|
import android.widget.Toast; |
|
public class MainHelloSpinner extends Activity { |
|
public void onCreate(Bundle savedInstanceState) { |
|
super .onCreate(savedInstanceState); |
|
setContentView(R.layout.main); |
|
Spinner spinner = (Spinner)findViewById(R.id.s1); |
|
ArrayAdapter adapter = ArrayAdapter.createFromResource( |
|
this , R.array.xuexings, android.R.layout.simple_spinner_item); |
|
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); |
|
spinner.setAdapter(adapter); |
|
OnItemSelectedListener oisl= new OnItemSelectedListener() { |
|
public void onItemSelected(AdapterView<?> parent, View view, |
|
Toast.makeText(MainHelloSpinner. this , "选择的血型: " + |
|
parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show(); |
|
public void onNothingSelected(AdapterView<?> parent) { |
|
spinner.setOnItemSelectedListener(oisl); |
效果如下: