Posted by : Unknown Monday, August 12, 2013



Hi again! For this post, I am going to keep working with the different layouts. On my previous post I tested the Linear Layout. Now, I am going to test the layout called List View. On the post about Relative Layout, I created a new Android application project named LayoutDemo. I am going to use the same project now to learn about the List View layout. 

The Java class ListView is one of the subclasses of the class ViewGroup found in the package android.view. The package provides classes for the user interface which includes screen layouts and ways for the user to interact with them. The user interface that you design can have more than one layout nested within another layout.

The List View layout displays a list of scrollable objects. The objects are inserted to the list using an Adapter. The Adapter is used as a bridge between the AdapterView layout and the data source. In other words, the Adapter provides access to the data source and then the data is converted into a view for the AdapterView layout. The AdapterView abstract class extends ViewGroup and can be used for your layout design if the content of the layout is dynamic and needs to be at runtime.

I am going to be using an ArrayAdapter, which is a subclass of Adapter, to access the objects and create a View for the AdapterView layout. The ArrayAdapter is used when the data source is an array. It will create a View for each object by using the toString() method and then place the contents in a TextView. To see how the ListView layout works, I am going to modify the activity_main.xml:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="20dp"
    tools:context=".MainActivity" >
 
</ListView>

The result it:

Graphical Layout - activity_main.xml


I am using the <ListView> tag to use the List View layout. I added a new id called list_view for this view so I can retrieve it. As you can see in the Graphical Layout tab, a default list is displayed.

To add items to the list, I am going to modify the MainActivity.java file. So far, your MainActivity.java file should look like this:

package com.android.layoutdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }
}

First, I will populate the array. I do this by adding the following code to the onCreate method:

String[] items = 
   new String[] {"Ice Cream", "Cake","Cookies""Brownies",
                 "Chips", "Candy", "Chocolate"};

Then, I declare a ListView object and use the method findViewById to retrieve the id named list_view added earlier. I do this by adding the following code after the String array named items:

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

Now, I am going to create a new ArrayAdapter by using the ArrayAdapter constructor ArrayAdapter(Context context, int resource, T[] objects) and then link it to the listView by using the setAdapter method. I do this by adding the following code:

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
             
listView.setAdapter(adapter);


The MainActivity.java file should now look like this:

package com.android.layoutdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              String[] items = 
                    new String[] {"Ice Cream", "Cake",                                                     "Cookies", "Brownies",
                                  "Chips", "Candy", "Chocolate"};
             
              ListView listView = 
                   (ListView) findViewById(R.id.list_view);

              ArrayAdapter<String> adapter =
                   new ArrayAdapter<String>
                  (this,  android.R.layout.simple_list_item_1, items);
             
             listView.setAdapter(adapter);       
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }
}

Test it by running the emulator. Right click the project LayoutDemo in the Project Explorer and select Run As -> Android Application. Wait for Eclipse to launch the application. It might take a while if you are starting the emulator. 

The result is:


LayoutDemo


As you can see, it is displaying a list of items with the values from the String array named items. Right now when you click one of the items nothing happens, but by adding a listener you can trigger an event. To do this, the method onItemClick needs to be implemented to handle the event trigger:

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

The method onItemClick is an unimplemented method of the class OnItemClickListener, which is going to be link to the ListView object by using the method setOnItemClickListener. The parameter named position is the position of the view in the adapter and id is the row id of the clicked item. To do this, add the following code after listView.setAdapter(adapter); :

listView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, 
                            int position, long id) {
                           
      String message = "The item selected is in row: " + position+1;
      Toast.makeText(getApplicationContext(), message
                    , Toast.LENGTH_LONG).show();              
      }
 });

The result is:

Selected Item

When you click on an item, a message should display. I did this by adding a Toast. The Toast class lets you display a message to the user. By using the static method makeText, the application will display the String message: "The item selected is in row: " + position+1 with duration Toast.LENGTH_LONG. One is added to the parameter position because the row count starts at zero. Finally, the method show() displays the Toast.

Display of Toast

You can also remove items from the list by using the method remove. To do this, modify the MainActivity.java file:

package com.android.layoutdemo;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              String[] items = new String[] {"Ice Cream", "Cake"
                                         ,"Cookies","Brownies""Chips",                                           "Candy", "Chocolate"};
             
              final ArrayList<String> itemList = 
                   new ArrayList<String>();
              for(int i = 0; i < items.length; i++){
                     itemList.add(items[i]);
              }
             
              ListView listView = 
                (ListView) findViewById(R.id.list_view);

           final ArrayAdapter<String> adapter =
                     new ArrayAdapter<String>(this
                    , android.R.layout.simple_list_item_1, itemList);
          
           listView.setAdapter(adapter);
          
           listView.setOnItemClickListener(new OnItemClickListener() {

           @Override
           public void onItemClick(AdapterView<?> parent, View view, 
                                    int position, long id) {
              Toast.makeText(getApplicationContext(), "Deleted " +                         adapter.getItem(position), Toast.LENGTH_LONG).show();
              itemList.remove(position);
              adapter.notifyDataSetChanged();         
           }
        });
   }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
              getMenuInflater().inflate(R.menu.main, menu);
              return true;
       }
}


The result is:

Deleted Item


As you can see, it deletes the item when clicked and displays a message of the item deleted. In my case, I deleted the item Cookies. 

First, I added an ArrayList called itemList and filled it up with the String array called items by using this code:

final ArrayList<String> itemList = new ArrayList<String>();
for(int i = 0; i < items.length; i++){
          itemList.add(items[i]);
}

Then, I modified the ArrayAdapter constructor so the data source would be the ArrayList itemList:

    final ArrayAdapter<String> adapter =
         new ArrayAdapter<String> (this,
                android.R.layout.simple_list_item_1, itemList);


Finally, I modified the onClick method so it would display a new message of the item deleted by using a Toast and using the method remove from the ArrayList class the item is deleted from the list. The method notifyDataSetChanged from the ArrayAdapter class should be called at the end so the view refreshes. 

On my next post, I will try the other layout GridView. Thank you for reading. Feel free to leave comments, subscribe, or follow me on Google+.






{ 2 comments... read them below or Comment }

      

Followers

Powered by Blogger.

Translate

Google Search

Support Blog

- Copyright © Learning Android Development -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -