我想用arraylist中的项目创建并填充listview

时间:2019-05-14 21:03:38

标签: java android listview arraylist

我已经创建了这个数组列表,并且在切换的情况下,我得到了“德里”数组列表的值。我想做的是创建一个Listview,按下按钮后,该列表将填充arraylist的项目。我能够使这些项目显示在textview上,但是我无法在listview中实现

            public void onItemSelected(AdapterView<?> parentView, View 
            selectedItemView, int myPosition, long myID) {
            ArrayList<String> delhi = new ArrayList<String>();

            delhi.add("Virgin Atlantic – London Heathrow");
            delhi.add("British Airways – London Heathrow");

            String country = spinner.getSelectedItem().toString();
            switch (country){
                case "Delhi":
                    record = delhi.get(0);
                    //record1 = delhi.get(1);

                    break;
                case "Hongkong":
                    //do something
                    break;
                // etc,etc,etc
            }
        }

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

        }


    });

2 个答案:

答案 0 :(得分:0)

您需要像Using lists in Android wth ListView一样为列表视图实现ArrayAdapter,但是我建议您使用RecyclerView来实现您想要的Simple Android recycler view example

目标

答案 1 :(得分:0)

您需要一个ArrayAdapter来适应您的ArrayList。 让我给你举个例子。

public class MainActivity extends Activity {

private ListView mListView;

public void onCreate(Bundle saveInstanceState) {
     setContentView(R.layout.your_layout);

     mListView = (ListView) findViewById(R.id.mListView);

     // Your array list.
        ArrayList<String> delhi = new ArrayList<String>();
        delhi.add("Virgin Atlantic – London Heathrow");
        delhi.add("British Airways – London Heathrow");

     // This is the array adapter, it takes the context of the activity as a 
     // 1st parameter, the type of list view as a 2nd parametr and your 
     // array as a 3rd parameter. android.R.layout.simple_list_item_1 
     // consists of a layout with TextViews.
     ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(
             this, 
             android.R.layout.simple_list_item_1,
             delhi );
     // Setting up your Adapter.
     mListView.setAdapter(mArrayAdapter); 
  }
}

将其放在OnClickListener中会在按下按钮时启动它。