ListView

ListView in Android


In this tutorial we will learn how to create a simple listview using Array.

ListView:
Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database.


  • Create a new project File->New->NewProject->SimpleListView.
  • Now create a ListView in activity_main.xml
File: activity_main.xml:

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
tools:context="com.exampl.hss_24.simplelistview.MainActivity">

<ListView      
android:id="@+id/listView"       
android:layout_width="match_parent"       
android:layout_height="match_parent">
</ListView>

</RelativeLayout>
  • Now create a layout file in res->layout->New->layout resource file
File: list_cell.xml:

<TextView    
android:id="@+id/text"    
android:textColor="#3F51B5"    
android:layout_width="match_parent"    
android:layout_height="70dp"    
android:padding="10dp"    
android:textStyle="bold"    
android:textSize="20sp"    
android:gravity="center_vertical"
xmlns:android="http://schemas.android.com/apk/res/android" />
  • Now copy and paste a MainActivity.java code in MainActivity.java file
File: MainActivity.java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    //    Array    
    String[] Android = {"Cupcake","Donut","Eclair","Froyo","Gingerbread","Honeycomb",
            "IceCream Sandwich","Jelly Bean","Lollipop","Marshmallow"};
    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //        Inflate array in layout        
        ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.list_cell,Android);

        //        show adapter in listView        
        ListView listView = (ListView)findViewById(R.id.listView);
        listView.setAdapter(adapter);
    }
}

Now run the Application:




















Thank You !!!!!
Please share follow if you like...

Comments