In this tutorial you will learn about the Android ListView and its application with practical example.
Android ListView
ListView is a view from which we can display group of items in vertical scrollable list. List items are automatically inserted with the help of adapter.
Adapter is a bridge UI component and data source, It pulls data from database or an array.
Lets understand ListView by an example, Create an project for ListView and define ListView in xml like below code:
1 2 3 4 5 6 |
<ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview" android:divider="@color/black" android:dividerHeight="2dp" /> |
ListView Attributes:
Width : Used for giving Width of ListView.
Height : Used for giving Height of ListView.
ID : It uniquely identify the View.
Divider : It can be drawable or color which drawn between listview item.
Divider Height : This is the height of divider.
Let see how your layout will look after draw ListView .
Now Its time to move on Activity Coding Part :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.example.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity { String[] str_arr = {"Android", "Java", "Paython", "C", "PHP", "C++", "C#", "JavaScript", "Go", "Swift"}; ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.listview); ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, str_arr); lv.setAdapter(adapter); } } |
So here is the code for ListView , I have used String Array which is bind with an ArrayAdapter, As we discussed above that Adapter is used to pull data from Database or an Array, So here is the example of ArrayAdapter which is pulling data from String array and then set into ListView.
ArrayAdapter is used when your data source is in array format.
In above image you can see your created list. So its simple ListView in which we used an ArrayAdapter . In next module we will learn Custom ListView using BaseAdapter.