Spinner(二)——简单使用完整示例

时间:2022-03-20 20:49:15

MainActivity如下:

package cc.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* Demo描述:
* Spinner简单使用的完整示例
*
* 注意事项:
* 这里的simple_spinner_item和simple_spinner_dropdown_item
* 我们均使用系统自带的布局
*/
public class TestSpinnerActivity extends Activity {
private Spinner mSpinner;
private ArrayAdapter<String> mAdapter ;
private String [] mStringArray;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}

private void init(){
mSpinner=(Spinner) findViewById(R.id.spinner);
mStringArray=getResources().getStringArray(R.array.test_string_array);
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mStringArray);

//设置下拉列表风格
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(mAdapter);
//监听Item选中事件
mSpinner.setOnItemSelectedListener(new ItemSelectedListenerImpl());

}

private class ItemSelectedListenerImpl implements OnItemSelectedListener{
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position,long arg3) {
System.out.println("选中了:"+mStringArray[position]);
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {


}

}
}



main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>


arrays.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string-array name="test_string_array">
<item>无</item>
<item>失眠</item>
<item>贫血</item>
<item>脱发</item>
<item>疲惫</item>
<item>烦躁</item>
<item>偏胖</item>
<item>偏瘦</item>
<item>白发</item>
<item>头痛</item>
<item>近视</item>
<item>弱视</item>
<item>耳鸣</item>
</string-array>

</resources>