0% found this document useful (0 votes)
10 views7 pages

Create ListView in Android: XML & Java

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

Create ListView in Android: XML & Java

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CREATING A

LISTVIEW IN
ANDROID
Defining list data in XML and populating ListView with ArrayAdapter
What is a ListView?
◦ A ListView displays a vertical scrollable list of items.
◦ Each item is a View (usually a TextView).
◦ Data is managed by an Adapter (e.g., ArrayAdapter, CursorAdapter,
or custom).

◦ Example XML:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Defining List Data in [Link]
<string-array name="programming_languages">
<item>Java</item>
<item>Kotlin</item>
<item>Python</item>
<item>C++</item>
<item>Swift</item>
</string-array>
Loading Data from XML into
ListView
◦ ListView listView = findViewById([Link]);

◦ String[] languages =
getResources().getStringArray([Link].programming_languages);

ArrayAdapter<String> adapter = new ArrayAdapter<>(


this, [Link].simple_list_item_1, languages);

◦ [Link](adapter);
Populating from Java Array
String[] cities = {"Beirut", "Tripoli", "Byblos", "Sidon"};

ArrayAdapter<String> adapter = new ArrayAdapter<>(


this,
[Link].simple_list_item_1,
cities);

[Link](adapter);
Handling Click Events

[Link]((parent, view, position, id) -> {


String selected = (String) [Link](position);
[Link](this, "You selected: " + selected,
Toast.LENGTH_SHORT).show();
});
Updating a ListView Dynamically
• When the data in the adapter changes, the ListView does NOT
update automatically.

• To refresh the display after modifying the underlying data (e.g.,


adding, removing, or editing items):

[Link]();

• This tells the ListView that its data has changed and it should redraw
the visible items.

Example:
[Link]("New Item");
[Link]();

You might also like