[android]代码库
1.MainActivity.java
package com.example.acer.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.province, android.R.layout.simple_spinner_item);
//定义下拉菜样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//为spinner设置适配器
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
Toast.makeText(parent.getContext(), "你来自的省份是: " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="@string/planet_prompt"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
3.res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="planet_prompt">你来自的省份是</string>
<string name="app_name">测试Spinner</string>
<string-array name="province">
<item>广东</item>
<item>广西</item>
<item>湖南</item>
<item>河南</item>
<item>福建</item>
</string-array>
</resources>