main.xml
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools=
"http://schemas.android.com/tools"
android:layout_width=
"match_parent"
android:layout_height=
"match_parent"
tools:context=
".MainActivity"
>
<Spinner android:id= "@+id/spinner" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:layout_centerHorizontal= "true" ></Spinner> </RelativeLayout> |
MainActivity.java
package com.example.spinnertest;
import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; public class MainActivity extends Activity { private Spinner spn; private static final String[] choices = { "O型", "A型", "B型", "AB型", "其他"}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); spn = (Spinner)findViewById(R.id.spinner); ArrayAdapter< String> adapter = new ArrayAdapter< String>( this, android.R.layout.simple_spinner_item, choices); //设置下拉列表的风格 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spn.setAdapter(adapter); spn.setOnItemSelectedListener( new Spinner.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { arg1.setVisibility(View.VISIBLE); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } |
写错了也不错报错,但是运行时就会出错。