List Controls in Android

ListView GridView and ExpandableListView in Android are very important elements that you can use for laying out our data in XML. All these elements are used for almost same purpose but the layout style is different. I have already written an android tutorial if you have just started android development. I would suggest you to read those parts as well on Getting Started with Android Studio. In this part, I would just be showing you how to add a list view, grid view and expandable list view in xml and how to add data into these elements. I would assume that you already know java and XML some how. And I would suggest you all to follow along with me with your Android Studio in your system.

ListView GridView and ExpandableListView in Android

Open Android Studio and make a new empty project. Open a layout file in the main app > res > layout > activity_main.xml. Inside this file you will have a text view and design view of you xml file. I will be showing you each layout element one by one.

1. List View

Open the text view of activity_main.xml file and you inside the default linear layout, you need to add few more controls. What you need to do is to simply replace your default XML code with the below one.

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/myedittext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:hint="Write something" />
        <Button
            android:id="@+id/mybutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:text="Add" />
    </LinearLayout>

    <ListView
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_marginTop="20dp"/>
</LinearLayout>

I hope that you know what going on here. Inside the main linear layout, I have added a new linear layout for edit text and button. I should be familiar with the attributes of these properties. Out side the internal linear layout, I have added a listview for data to be added in it through above edit text when button will be pressed. Now when you will see the design view of this XML, it will be look like this.

list

Now we are done with our layout for list view. Open MainActivity.java file from app > java > your_package_name > MainActivity.java. Inside the MainActivity class (but above the OnCreate method, just add following piece of code to.

Button mButton;
EditText mEditText;
ListView mListView;
ArrayAdapter mArrayAdapter;
ArrayList mNameList = new ArrayList();

ArrayAdapter class is used to notify list view that data have been changed in ArrayList. ArrayList is used to store data to be added in ListView. You night be getting errors that you are supposed to import required packages. You can right click on the error and click on import package. But in order to do this every time, there is an efficient way to do this. Go to Files > Settings > Editor > General > Auto Import  and check the Add unambiguous imports on the fly as shown in the image below.

admin-ajax.php

Click on Apply button on this settings window. What it will do is, it will add all required import lines based on your code automatically. Now get back to the MainActivity.java file. Inside the OnCreate method, you need to get the reference to the elements added in the layout. Other then this, you need to set the array adapter for array list and set the onclick events to button and list view items. Simply add change your onCreate method with the below one.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mButton=(Button)findViewById(R.id.mybutton);
    mEditText=(EditText)findViewById(R.id.myedittext);
    mListView=(ListView) findViewById(R.id.mylistview);

    mArrayAdapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, mNameList);
    mListView.setAdapter(mArrayAdapter);

    mButton.setOnClickListener(this);
    mListView.setOnItemClickListener(this);
}

You might be facing some errors on button click listeners and list view listeners. In order to remove those error, change your class declaration at the top to implement OnClickListenner and Listview item click listener just like below one.

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener

For button on click listener, we need to have an onClick method. So add the following method, just below the onCreate method.

@Override
public void onClick(View v) {
    mNameList.add(mEditText.getText().toString());
    mArrayAdapter.notifyDataSetChanged();
}

The above code will get the text written in edit text and add that text in the list view. Now the last we need to add is a method for onItemClickListener for the list view. So add the following method just below the onClick method.

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(getApplicationContext(), "You clicked "+mNameList.get(position)+" at position "+position, Toast.LENGTH_SHORT).show();
}

Now after running our app, we can add items by writing it in edit text and click on the add button. When we will click on any added item on the list view, a toast will appear showing which item we have click at which position as shown in the image below.

2015-11-17_01h46_00-286x400

2. GridView

We have seen ListView in detail. Now its time to see one more cool element called Grid View. Grid View is an element which layouts its items in the form of rows and columns. It requires almost same things like data array and array adapter to show the data in this grid view. You might have seen some wallpapers apps and android, most of those apps use grid view for laying out these items. There are some important attributes that has to be known before start adding grid view in your app. Before explaining you those attributes, lets first add the given code inside your main relative layout (or any other layout) tag in your activity_main.xml file.

<GridView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/myGridView"
    android:numColumns="auto_fit"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp"
    android:gravity="center"
    android:horizontalSpacing="10dp" />

There is an attribute numColumns, which I have set to auto_fit. You can directly set its value to numbers but that will not be fine for multiple screen sizes. Column width attribute should be set to specify the width of one column. Stretch mode should be set to column width to stretch the element column wise. Horizontal and vertical spacing attribute should be set the specify the space between two columns and two rows. When you will add the grid view layout, it should be look like the image below, when switching to the design view of xml.

2015-11-20_23h46_31

Now before moving further to get the reference of this element in MainActivity, we need to make a new class which will extends a BaseAdapter class. We are making a separate adapter class for it, because it requires some extra methods in it to work. So, just make a new class called GridAdapter inside your main package and extend it with BaseAdapter. What you need to do now is to add given code inside the GridAdapter class.

private Context myContext;
public GridAdapter(Context c)
{
    myContext=c;
}
public int getCount()
{
    return gridItems.length;
}
public Object getItem(int position)
{
    return null;
}
public long getItemId(int position)
{
    return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
    TextView myStrings;
    if (convertView == null)
    {
        myStrings = new TextView(myContext);
        myStrings.setLayoutParams(new GridView.LayoutParams(80, 80));
        myStrings.setTextSize(12);
    }
    else
        myStrings = (TextView) convertView;
    myStrings.setText(gridItems[position]);
    return myStrings;
}
public String [] gridItems = {"abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yza",
        "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yza"};

Remove the required import package errors from the given code. In the getView method above, I have set the text view type variable to be shown as the items of grid view. You can add any other item here as well, like images, videos etc. Now come back to the MainActivity.java class. Inside the OnCreate method, just below the setContentView method call, add the following code.

GridView gridview = (GridView) findViewById(R.id.myGridView);
gridview.setAdapter(new GridAdapter(this));

In the above code, we are setting up the adapter to that class. This was all we need to do in the main activity class. Now if you run your application, you should see the following output.

555


Now we want to set a click listener when an item on grid will be clicked. Adding a pop up message using toast when an item is clicked on grid view. In the MainActivity.java, inside the OnCreate method add the following code at the end.

final GridAdapter gridAdapter=new GridAdapter(this);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
    {
        Toast.makeText(getApplicationContext(), "You clicked " + gridAdapter.gridItems[position] + " at position " + position, Toast.LENGTH_SHORT).show();
    }
});

3. ExpandableListView

We are done with two important elements, now its time to see one more important element Expand able list view. What this element does is, it layouts items same as the simple list view, but which the drop down (combo box). Same the above elements, it is an element in XML. So, what you need to do is just to add the following code within the main relative (or any other) layout in your activity_main.xml file.

<ExpandableListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/expandableListView"
    android:dividerHeight="0.5dp"
    android:divider="#A4C702"/>

Now we need to have two more xml files, one for group items and other for child items for expand able list view. So, create two new XML files and name these files as group_activity.xml and child_activity.xml. Inside the group_activity.xml file, just add the following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFF0">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/GTextView"
        android:textSize="20dp"
        android:padding="10dp"
        />
</LinearLayout>

In the child_activity.xml file, copy the similar above code but change the value of id attribute to CTextView (rather GTextView) and background of linear layout to #FFFFD0.

We need to write some java code in order to perform the exact and proper functionality of expandable grid view. I am going to show you this element with an example of Games categories and lists of games. We have our MainActivity.java class by default, but we need to make two more java files for the functionality of this amazing element. So, make a new java file under the same package, where default MainActivity.java file exists and name this file as GroupData. Within this class, Add the following piece of code.

public static HashMap<String, List<String>> getInfo()
{
  HashMap<String, List<String>> myGames=new HashMap<String, List<String>>();
  List<String> Sports_Games = new ArrayList<String>();
  List<String> Action_Games = new ArrayList<String>();
  List<String> Strategy_Games = new ArrayList<String>();
  Sports_Games.add("Tennis 3D");
  Sports_Games.add("Soccer");
  Sports_Games.add("Cricket 3D");
  Action_Games.add("Shadow Fight");
  Action_Games.add("Max Payne 3"); 
  Action_Games.add("Call of Duty");
  Strategy_Games.add("3D chess");
  Strategy_Games.add("Pipe Master");
  Strategy_Games.add("Paper Defence");
  myGames.put("SportsGames", Sports_Games);
  myGames.put("ActionGames", Action_Games);
  myGames.put("StrategyGames", Strategy_Games);
  return myGames;
}

There is a hash map variable to shore all the data in the expandable list view. With in this hash map, I have added three sub lists for the three categories of games and name of those games. This code is in the method called getInfo, for data adapter to get data by calling this method.

Same as in grid view and list view, we used an adapter for data to be shown visually. In this case, we need an adapter again for expandable list view. So, make a new java class under the same package and name this java file as GamesAdapter. Once the class has been created, extend this class with BaseExpandableListAdapter. This parent class need around 10 method to be overridden in the child (GamesAdapter) class. Don’t import those unimplemented methods for now. Because all those methods require some code to be added within them. For your ease, just add the following piece of code within that class ( called Games Adapter) and add the required imports above this class.

private HashMap<String, List<String>> myGames;
private List<String> myGames_List;
private Context context;

public GamesAdapter(HashMap<String, List<String>> myGames_, List<String> myGames_List_, Context context_)
{
    myGames=myGames_;
    myGames_List=myGames_List_;
    context=context_;
}

@Override
public int getGroupCount() {
    return myGames_List.size();
}

@Override
public int getChildrenCount(int groupPosition) {
    return myGames.get(myGames_List.get(groupPosition)).size();
}

@Override
public Object getGroup(int groupPosition) {
    return myGames_List.get(groupPosition);
}

@Override
public Object getChild(int groupPosition, int childPosition)
{
    return myGames.get(myGames_List.get(groupPosition)).get(childPosition);
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    String group_txt=(String) getGroup(groupPosition);
    if(convertView==null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.group_activity, parent, false);
    }
    TextView group_textView= (TextView)convertView.findViewById(R.id.GTextView);
    group_textView.setTypeface(null, Typeface.BOLD);
    group_textView.setText(group_txt);
    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
    String child_txt = (String) getChild(groupPosition, childPosition);
    if(convertView==null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.child_activity, parent, false);
    }
    TextView child_textView= (TextView)convertView.findViewById(R.id.CTextView);
    child_textView.setText(child_txt);
    return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

There is a bunch of code written above but there are two important method that has to understood. One is the getChildView and other is the getGroupView. Now we are done with the main part for the functionality of expand able list view. What we need to do now is to update our MainActivity.java file to finish this thing up. Open your MainActivity.java file and declare following few variables just below the class declaration (but outside any method).

ExpandableListView myExpandAbleListView;
List<String> myGames;
HashMap<String, List<String>> myGames_Catagories;
GamesAdapter gamesAdapter;
myExpandAbleListView = (ExpandableListView) findViewById(R.id.expandableListView);
myGames_Catagories = GroupData.getInfo();
myGames= new ArrayList<String>(myGames_Catagories.keySet());
gamesAdapter=new GamesAdapter(myGames_Catagories, myGames, this);
myExpandAbleListView.setAdapter(gamesAdapter);

This was all that we needed to do in order to get expandable list view worked. Save all the files and make sure your don’t have any errors. Once we are done with all the above steps, lets see how it looks when we will run our app now.

2015-11-21_19h19_43-286x400

You can see in the above image, that I have expanded the Sports Games and see its child elements. I hope that you have got the idea of how expandable list view works. Now we need to do one thing more here is to set the click listener on each child element. To do that there is an event listener called on child click listener for expand able list view. What you need to do is to add the following piece of code within the onCreate method (but below the previous code written in this method).

myExpandAbleListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
    {
        Toast.makeText(getApplicationContext(), "You clicked " + myGames_Catagories.get(myGames.get(groupPosition)).get(childPosition), Toast.LENGTH_SHORT).show();
        return false;
    }
});

Now if you run this application, you will see the pop message will appear showing which item we have clicked as shown in the image below.

2015-11-21_19h40_59-288x400

You can see that I clicked on 3D chess child item, and it shows that you clicked 3D chess. You can perform any other function as well by clicking on any item. I have just shown you how click works by showing a pop up message.

I hope that you have leaned all these amazing elements in android. If any body face any problem or want to share more on this topic, just comment below this post. Thank you 🙂


Leave a comment

Design a site like this with WordPress.com
Get started