Android[初级教程]第四篇 Spinner控件
还是接上一篇,这次妖精们说了,不要用RadioButton控件了,不好看,还占地方,抓一个人,要占四个地方,那我抓一个人只要占一个地方就行了,于是用了Spinner控件,还是一次抓一个
main.xml如下
view plain
</pre><pre class="html" name="code"><?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">
<Spinner android:layout_height="wrap_content" android:id="@+id/spinner"
android:layout_width="wrap_content"></Spinner>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="@string/hello"
android:id="@+id/text"></TextView>
</LinearLayout>
Activity的java代码如下:
view plain
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.TextView;
public class ButtonDemoActivity extends Activity implements OnItemSelectedListener
{
private TextView text = null;
private Spinner spinner;
private String[] item = { "唐僧", "孙悟空 ", "猪八戒", "沙和尚" };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 通过ID查找到main.xml中的TextView控件
text = (TextView) findViewById(R.id.text);
// 通过ID查找到main.xml中的Spinner控件
spinner = (Spinner) findViewById(R.id.spinner);
//设定一个Array适配器,将数组数据放入适配器中
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.易做图_spinner_item, item);
//设置下拉列表的样式
adapter.setDropDownViewResource(android.R.layout.易做图_spinner_dropdown_item);
//对Spinner进行适配
spinner.setAdapter(adapter);
//Spinner中事件选择的监听
spinner.setOnItemSelectedListener(this);
}
private void updateText(String string)
{
// 将文本信息设置给TextView控件显示出来
text.setText(string);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long arg3)
{
String str = "这次妖精把" + item[position] + "抓住了!";
updateText(str);
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
}
你要说妖精们的事还真多,一会这样,一会那样的,用我们现在的话来说就叫"众口难调"啊,毕竟妖精多了去了,
摘自:kangkangz4的专栏
补充:移动开发 , Android ,