StackOverflow simple ArrayAdapter question
ArrayAdapter Guide
(includes info for simple arrayAdapter and custom arrayAdapter)
A ListView can display data from an ArrayList.
Here’s the simpler version that doesn’t require a custom ArrayAdapter class:
public class MainActivity extends AppCompatActivity { ArrayList things; ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); things = new ArrayList<>(); things.add("pizza"); things.add("ice cream"); things.add("tacos"); things.add("sushi"); lv = findViewById(R.id.things); ArrayAdapter<String> arrAdap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, things); lv.setAdapter(arrAdap); } }
Things to notice in the “simple” example:
- A ListView named lv is declared and instantiated.
(this ListView must also exist in the XML layout file and have an ID) - An ArrayList<String> named things created and items added to it
- An ArrayAdapter named arrAdap is declared and instantiated
- The ListView’s setAdapter() method is called to select arrAdap
The trickiest part is creating the ArrayAdapter. In this case, we used a default constructor for the ArrayAdapter class.
The arrayAdapter constructor method used above takes three arguments:
arrayAdapter(context, layout resource, ArrayList)
- context is the Activity object; simply enter “this” as the first argument if the arrayAdapter is being created in an Activity class such as MainActivity.java.
- layout resource is a layout (XML) file; you can use a custom XML layout, but in this example we are using a built-in simple layout (android.R.layout.simple_list_item_1) that only includes a TextView. (using this built-in layout saves you from creating a custom ArrayAdapter class)
- ArrayList is the list of items that you want to display. It can be any object type, but be sure to override its toString() method. Each object will be converted to a String before it is displayed in the ListView. (hint: go to your class java file and use Control+O to override a method)
For reference, here is the XML layout file used in the example above. The main thing to note is that it includes a ListView with an id.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/things" android:layout_width="395dp" android:layout_height="685dp" android:layout_marginTop="8dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>