基本视图——Spinner

作者:追风剑情 发布于:2015-9-7 21:49 分类:Android

一、配置strings.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string-array name="presidents_array">
  4. <item>John F. Kennedy</item>
  5. <item>Lyndon B. Johnson</item>
  6. <item>Richard Nixon</item>
  7. <item>Gerald Ford</item>
  8. <item>Jimmy Carter</item>
  9. <item>Ronald Reagan</item>
  10. <item>George H. W. Bush</item>
  11. <item>Bill Clinton</item>
  12. <item>George W. Bush</item>
  13. <item>Barack Obama</item>
  14. </string-array>
  15. </resources>

视图

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical"
  6. tools:context="${relativePackage}.${activityClass}" >
  7.  
  8. <Spinner
  9. android:id="@+id/spinner1"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:drawSelectorOnTop="true" />
  13. </LinearLayout>

代码

  1. package com.example.androidtest;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.AdapterView;
  7. import android.widget.AdapterView.OnItemSelectedListener;
  8. import android.widget.ArrayAdapter;
  9. import android.widget.Spinner;
  10. import android.widget.Toast;
  11.  
  12. public class SpinnerActivity extends Activity {
  13.  
  14. String[] presidents;
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_spinner);
  19. presidents = getResources().getStringArray(R.array.presidents_array);
  20. Spinner s1 = (Spinner) findViewById(R.id.spinner1);
  21. ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
  22. android.R.layout.simple_spinner_item, presidents);
  23. //下接列表显示为单选按钮
  24. /*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
  25. android.R.layout.simple_list_item_single_choice, presidents);*/
  26. s1.setAdapter(adapter);
  27. s1.setOnItemSelectedListener(new OnItemSelectedListener(){
  28.  
  29. @Override
  30. public void onItemSelected(AdapterView<?> parent, View view,
  31. int position, long id) {
  32. int index = parent.getSelectedItemPosition();
  33. Toast.makeText(getBaseContext(), "You have selected item : "+presidents[index],
  34. Toast.LENGTH_SHORT).show();
  35. }
  36.  
  37. /**
  38. * 当用户按下Back按钮时触发这一方法,撤销所显示的项列表。
  39. * 在这种情况下,没有任何项被选择,也不需要作任何处理。
  40. */
  41. @Override
  42. public void onNothingSelected(AdapterView<?> parent) {
  43. }
  44. });
  45. }
  46. }

运行效果

ssssssssssss.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号