我想从特定阵列列表中获取元素,具体取决于Spinner的所选值



我已经创建了多个arraylists,我想创建一个函数,根据旋转器从旋转器中选择的内容显示项目。

我创建的一些阵列

    ArrayList<String> delhi = new ArrayList<String>();
    delhi.add("Virgin Atlantic – London Heathrow");
    delhi.add("British Airways – London Heathrow");
    ArrayList<String> hongkong = new ArrayList<String>();
    hongkong.add("Virgin Atlantic – London Heathrow");
    hongkong.add("British Airways – London Heathrow");
    ArrayList<String> shanghai = new ArrayList<String>();
    shanghai.add("Virgin Atlantic – London Heathrow");
    shanghai.add("British Airways – London Heathrow");
    ArrayList<String> johannesburg = new ArrayList<String>();
    johannesburg.add("Virgin Atlantic – London Heathrow");
    johannesburg.add("British Airways – London Heathrow");

我创建的旋转器中的一些值

    spinner = (Spinner) findViewById(R.id.spinner);
    ArrayList<String> list = new ArrayList<>();
    list.add("Delhi");
    list.add("Hong Kong");
    list.add("Shargai");
    list.add("Johannesburg");
    list.add("Lagos");
    list.add("Antigua");
    list.add("Barbados");
    list.add("Grenada");
    list.add("Havana");
    list.add("Jamaica");

如果在旋转值更改时想要一个函数,请尝试将侦听器添加到ongreate方法中的旋转器:

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
            String country = spinner.getSelectedItem().toString();
            switch (country){
                case "Delhi":
               //do something
                    break;
                case "Hongkong":
              //do something
                    break;
             // etc,etc,etc
            }
        }

您可能想使用开关案例:

switch(value) {
case "Delhi":
 //Do something
break;
case "Hong Kong":
//Do something
break;
}

最新更新