Android Studio - ListView Basic Example

Hello people,

Its been a quite time that there has been no post regarding Android Examples on this blog. So Today we are going to write a very basic program
which is To display a list view in Android . We are going to use Android Studio for this Example too, as most of our previous examples were also in Android Studio.
So before I explain you more about Android Studio without wasting more of your time ,let us dig in the code .


So the very first question in your mind (if you are new in android ) would be what the hell is listview? Is it a collection like in Java?
No sorry it is not related to Collections in Java.

ListView is actually just a group of some items ,which can be scrolled in vertical position .For Example as you go into Settngs of your phone
you see a list of items like Network , Wifi, Bluetooth and many more in a vertical scrollable way.

So from does this ListView came from ? I mean you are wondering who's the father? :D
ListView and GridView are siblings with father Mr. AdapterView ... View is their SirName :p

I mean that both ListView and GridView are subclasses of AdapterView . So i shall not go into more details of their family and let me show a very basic example of
listView . In this example i ll just show a list of items and on clicking any of them u ll get a toast which show their name Thats it . Seems to be easy right ?
Its not too difficult but yes we have to write the whole code . :)


Step 1: Create a New Application

Let us first create a new Application in Android Studio.


Android ListView Example
Android ListView Example


Android ListView Example
Android Example

I gave Application name as ListViewExample .You can provide any values to the form Configure your project. and click Next.


Step 2: Select Target Android Device

Select Target Android Device on which output will be shown . For this I choose Phone View.



Step 3: Customize the Activity 


By Default the activity name is MainActivity . If you want to change that you can but rest of the things will be changed accordingly. I gave name as ListViewActivity


Android ListView Example
Android Example
Step 4: 

 After your Application is created you ll see the screen below with 3 main files :

1.*xxx*Activity.java
2. content_xxx.xml
3. activity_xxx.xml

xxx is will be the name which you choose in step 3.

Android ListView Example
Android Example
If you are wondering that there are two xml files content_listview.xml and activity_listview.xml and in which I should write the code then I tell you that you can add your widget or container in any xml file as content_list.xml is a part of activity_listview.xml only.


  Activity_listview.xml 



Android ListView Example
Android Example



Step 5: 

Now you need to add listview in xml file . I added it in content_listview.xml. You can add it in 2 ways :

1. Simply Drag listview container from left Explorer as shown in below screenshot :

Android ListView Example
Android Example
2. Second way is to add list view tag in content_listview.xml file as shown below :


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






Android ListView Example
Android Example

Step 6: Create a new activity.I named it as Button Activity

Now we need to add code in ListViewActivity.Java .For List Items we are using a String Array .

First , we need to Retrieve the ListView using method  findViewById. where listView is the id we gave while creating list view in content_listview.xml.


final ListView listView = (ListView) findViewById(R.id.listView);
   

Second, Define a new Adapter and assign that adapter to the listView variable we created above.


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);


        

listView.setAdapter(adapter);

   


Then , we have to define the onlick listener of listView which will run when user click on any of the item .In this code On Click of item a Toast is shown with item position no. and value of that item.
You can find below the whole ListViewActivity.java.

package javainhouse.com.listviewexample;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ListviewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Get ListView object from xml
       final ListView listView = (ListView) findViewById(R.id.listView);

        // Defined Array values to show in ListView
        String[] values = new String[] { "List View Item1",
                "List View Item 2",
                "List View Item 3",
                "List View Item 4",
                "List View Item 5",

        };
        
        // Define a new Adapter
       

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);


        // Assign adapter to ListView
        listView.setAdapter(adapter);

        // ListView Item Click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()   {


            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                        .show();

            }

        });
    }






    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_listview, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

   



Step 7: RUN and Output



Android ListView Example
Android Example


Android ListView Example
Android Example
You can see the Toast as well with Position and Listitem value .

If you like the post please press the Like Button below . If any errors , please comment below we ll be happy to solve it.

Post a Comment