Array Adapters

Array adapters are used to populate items as in the list view.

List View contains repetitive Views.

Lets say we have a text views which we want to display inside of a ListView.

Step 1:

Create a ListView ( To be used as a container of our TextViews):

<FrameLayout...>
<ListView
android:id="@+id/listview_forecast"
/>
</FrameLayout>

Step 2:

Create a text view layout resource file, eg: list_item_forecast.xml with root view as a TextView

<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/list_item_forecast_textview">

</TextView>

Step 3:

In your Activity File

  • Store the current view
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
  • Create a mock data
String data[] = {
"Data1 ", "Data2", "Data3", "Data4"
};
  • Store this in a list
List<String> listData = new ArrayList<String>(Arrays.asList(data));
  • Create an Array Adapter

It takes 4 parameters:

  1. Current Context (this Activity)
  2. The name of the layout file where you wish to populate the data
  3. The id of the text view where you wish to populate the text (in TextView).
  4. List of data items
ArrayAdapter<String> mForecastAdapter;

mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
listData);

Step 4:

  1. Grab the reference to the ListView where we wish to set this adapter
ListView listview =(ListView) rootView.findViewById(R.id.listview_forecast);

2. Set the adapter to the listview

listview.setAdapter(mForecastAdapter);

Done!

Like what you read? Give Yask Srivastava a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.