书中只是简单写了选择的界面,没有写出选择之后的结果显示,我做了进一步功能。
MainActivity.java
-
public class MainActivity extends Activity
-
{
-
Spinner spinner;
-
Spinner spinner1;
-
TextView tv;
-
String[] arr = { "孙悟空", "猪八戒", "唐僧" };
-
Button butt;
-
int Position;
-
@Override
-
public void onCreate(Bundle savedInstanceState)
-
{
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
// 获取界面布局文件中的Spinner组件
-
spinner = (Spinner) findViewById(R.id.spinner);
-
spinner1 = (Spinner) findViewById(R.id.spin1);
-
tv = (TextView) findViewById(R.id.tv);
-
butt = (Button) findViewById(R.id.butt);
-
// 创建ArrayAdapter对象
-
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
-
android.R.layout.simple_list_item_multiple_choice, arr);
-
// 为Spinner设置Adapter
-
spinner.setAdapter(adapter);
-
butt.setOnClickListener(new View.OnClickListener() {
-
@Override
-
public void onClick(View v) {
-
String string=spinner.getSelectedItem().toString();
-
String string1 = spinner1.getSelectedItem().toString();
-
tv.setText(string1+" + "+string);
-
}
-
});
-
}
-
}
|
XML文件
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="vertical"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent">
-
<!-- 定义了一个Spinner组件,指定显示该Spinner组件的数组 -->
-
<Spinner
-
android:id="@+id/spin1"
-
android:layout_marginTop="40dp"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:entries="@array/books"
-
android:prompt="@string/tip"/>
-
<Spinner
-
android:id="@+id/spinner"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:prompt="@string/tip"/>
-
-
<TextView
-
android:id="@+id/tv"
-
android:layout_marginTop="30dp"
-
android:layout_gravity="center_horizontal"
-
android:text="选择"
-
android:textColor="@android:color/holo_red_light"
-
android:textSize="30sp"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"/>
-
<Button
-
android:id="@+id/butt"
-
android:layout_marginTop="30dp"
-
android:text="确认"
-
android:textSize="30dp"
-
android:layout_gravity="center_horizontal"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"/>
-
</LinearLayout>
|
效果: