list view组件和spinner组件使用方法类似,从string.xml中通过entries获取数据显示。但如果要显示的列表项无法在执行前确定,或是要在程序执行的过程中变更选项内容,通过entries获取数据就行不通了。
在这里需要用到ArrayAdapter。ArrayAdapter对象会从指定的数据源中取出每一项数据,再提供给spinner组件来显示。
我在这里举个栗子:比如我们平常买奶茶,有些是可以常温,但是有些只有加冰或去冰。
布局文件代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:orientation="vertical" 8 tools:context="com.hs.example.exampleapplication.SpinnerActivity"> 9 10 <Spinner 11 android:id="@+id/drink" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content"> 14 15 </Spinner> 16 17 <Spinner 18 android:id="@+id/temp" 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content"> 21 22 23 </Spinner> 24 25 <Button 26 android:gravity="center" 27 android:layout_width="match_parent" 28 android:layout_height="wrap_content" 29 android:onClick="ShowOrder" 30 android:text="下订单"/> 31 32 <TextView 33 android:id="@+id/Text_order" 34 android:layout_width="match_parent" 35 android:layout_height="match_parent" 36 android:text=""/> 37 38 </LinearLayout>
逻辑代码如下:
1 public class SpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{ 2 3 Spinner drink , temp; 4 TextView order; 5 String [] drinks = {"珍珠奶茶","波霸奶茶","丝袜奶茶","金桔柠檬"}; 6 String [] tempSele1 = {"加冰","去冰","常温"}; 7 String [] tempSele2 = {"加冰","去冰"}; 8 9 @Override 10 protected void onCreate(Bundle savedInstanceState) { 11 super.onCreate(savedInstanceState); 12 setContentView(R.layout.activity_spinner); 13 14 drink = this.findViewById(R.id.drink); 15 //创建array adapter对象 选单未打开时的样式 饮品选项 16 ArrayAdapter<String> drinkAd = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,drinks); 17 drinkAd.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//设置下拉选单的样式 18 drink.setAdapter(drinkAd); //设置adapter对象 19 drink.setOnItemSelectedListener(this); 20 21 temp = this.findViewById(R.id.temp); 22 order = this.findViewById(R.id.Text_order); 23 24 25 } 26 27 @Override 28 public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 29 String [] tempSet; 30 if(i == 3){ //购买金桔柠檬时,没有常温选项 31 tempSet = tempSele2; 32 }else{ 33 tempSet = tempSele1; 34 } 35 ArrayAdapter<String> tempAd = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,tempSet); 36 tempAd.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 37 temp.setAdapter(tempAd); 38 } 39 40 @Override 41 public void onNothingSelected(AdapterView<?> adapterView) { 42 43 } 44 45 public void ShowOrder(View view){ 46 String msg = drink.getSelectedItem() + "|" + temp.getSelectedItem(); 47 order.setText(msg); 48 } 49 }
运行效果如下: