survey-2316468_1280

Create A List View Using Custom Adapter

Hello ,welcome to Bunkerspoint. In this post, we will see how to make a List view using custom adapter. This topic may be a bit intimidating so we will keep it easy by using text view only.

In this session we are going to create an app using list view which will display two text views called name and number using Array adapter.

  • open your android Studio app.
  • Click on new project-> give any name as you like.
  • Choose an empty activity-> click on next.
  • Don’t change any settings -> click on finish.
  • project may take some time to build and sync itself.
  • Copy the following code mainactivity.xml file. In the below given code, we create list view and assign it a id called “custom_list”.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

      />

</RelativeLayout>
  • copy the following code into list_item.xml. In list_item.xml ,we create two text views and assign each of them an id so that when list is created we could use ids to display the data into list.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_margin="24dp">


    <TextView
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="10dp"
        android:layout_margin="10dp"
        android:textSize="20dp"
        tools:text="1"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:paddingLeft="20dp"
        android:layout_margin="10dp"
        android:textSize="20dp"
        tools:text="maharana"/>

</LinearLayout>
  • Create a new class called Acttivity(any name you want I kept mine as Acttivity) which will use to define your class and store the data in it. We created two objects of String data type.

We created a constructor to extract values from array adapter and return it in getmName and get mNumber methods. So ,that it is displayed. Copy the following code into Acttivity.java class.

package com.example.bunkersdemo2;

public class Acttivity {

    private String mNumber;

    private String mName;



    public Acttivity(String vNumber,String vName){

        mNumber=vNumber;
        mName=vName;

    }


    public String getmNumber() {
        return mNumber;
    }

    public String getmName() {
        return mName;
    }
}
  • create a new class called Acttivity adapter(name whatever you want) and extend it ArrayAdapter(in my case ArrayAdapter).Now we create our own custom constructor which takes two arguments ,context (it will be used to inflate the layout file)and list(to populate the items in the list). The list we are using is ArrayList.

Then we call a method called getView method. we create a variable called listItemView to convertView. If listItemView is null then we inflate the listItemview using the LayoutInflater.inflate(). We use getitem() method to get the position of the object. We update the text views using findviewbyid() and update the data of object in list_item xml using the id number and name and return the listItemView.

package com.example.bunkersdemo2;

import android.app.Activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ActtivityAdapter extends ArrayAdapter<Acttivity> {


    public ActtivityAdapter(Activity context, ArrayList<Acttivity> activity) {
        super(context, 0,activity);
    }



    @Override
    public View getView(int position,  View convertView,  ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        Acttivity currentActivity=getItem(position);


        TextView number = (TextView)listItemView.findViewById(R.id.number);
        number.setText(currentActivity.getmNumber());


        TextView name = (TextView)listItemView.findViewById(R.id.name);
        name.setText(currentActivity.getmName());

        return listItemView;
    }
}
  • copy the following code into MainActivity.java file. We are done creating Adapter and list item xml .So in mainactivity.java file. we create array list called activity and enter the Acttivity objects which will be displayed. We get a reference to the list view and attach it to the adapter in the list view using findviewbyid () method. Add some items in the arrayList by add() method.
package com.example.bunkersdemo2;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

        ArrayList<Acttivity> activity = new ArrayList<Acttivity>();

        activity.add(new Acttivity("1", "Maharana"));
        activity.add(new Acttivity("2", "Shruti"));
        activity.add(new Acttivity("3", "Maharaj"));
        activity.add(new Acttivity("4", "Maharani"));
        activity.add(new Acttivity("5", "Maha"));
        activity.add(new Acttivity("6", "Marna"));
        activity.add(new Acttivity("7", "Mahana"));
        activity.add(new Acttivity("8", "Maharana2"));
        activity.add(new Acttivity("9", "Maharana3"));
        activity.add(new Acttivity("10", "Maharana4"));
        activity.add(new Acttivity("11", "Maharana5"));
        activity.add(new Acttivity("12", "Maharana6"));
        activity.add(new Acttivity("13", "Maharana7"));
        activity.add(new Acttivity("14", "Maharana8"));
        activity.add(new Acttivity("15", "Maharana9"));
        activity.add(new Acttivity("16", "Maharana0"));


        ActtivityAdapter adapter= new ActtivityAdapter(this,activity);
        ListView listView=(ListView) findViewById(R.id.custom_list);
        listView.setAdapter(adapter );

    }
}

OUTPUT


In this post, you have seen how to create a arraylist using custom adapter and how to implement it in your app. you can try and implement in different examples to understand. If you want more information you can go to documentation here. It is always a good practice to read the documentation.
Thank you for reading and keep following bunknerspoint.

getting started with android studio

LISTVIEW IN ANDROID

Hello, welcome to bunkerspoint ,this topic is based on list view in android with example. So what’s list view in android? In android developers official website it says,“A list view is an adapter view  that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter  as needed, such as to display new views as the user scrolls up or down”.

In simple, a list view is a view that contains list items and display them in vertical scrollable, which allows user to scroll the list items up and down vertically. ListView uses adapter to bind data from it to display in ListView. Think of an adapter as a middleman between Adapter view and any other view such as ListView , GridView etc.

USING ADAPTER IN LISTVIEW

ListView is a subclass of AdadpterView and they can be populated by binding to an Adapter. An Adapter retrieves data and represents those data. There are some common adapters which are frequently used such as ArrayAdapter, BaseAdapter, CursorAdapter etc..


In this tutorial, we are going to make use of ArrayAdapter. We are going to see how to implement listView in android studio using ArrayAdapter.
After following this tutorial, you would have the following output.

Lets begin with creating activity_main.xml

Create a lisView inside the activity_main.xml and give it a id of listView.

<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for the main screen -->
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp”
    android:paddingRight="16dp"
    android:paddingTop="16dp" />

Create a new layout resource file and name it as list_items

<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16dp"
    android:textStyle="bold" >
</TextView>

In mainActivity.java add this code snippet.

package com.bunkerspoint.android.listView;

import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
 import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Manuj");
    arrayList.add("Pratik");
    arrayList.add("Yash");
    arrayList.add("Yatendra");
    arrayList.add("Yagnesh");
    arrayList.add("Mayur");
    arrayList.add("Manuj");
    arrayList.add("Raju");
    arrayList.add("Yadav");
    arrayList.add("Dhoni");


    ArrayAdapter<String>arrayAdapter = new      ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,arrayList);
    // Get a reference to the ListView, and attach the adapter to the listView.
    ListView listView = (ListView) findViewById(R.id.listview_flavor);
    listView.setAdapter(arrayAdapter);
 }
}

The above code snippet creates a listView with list items as shown below.

HANDLE CLICK LISTENERS IN LISTVIEW

The above code snippet only shows the list item but listview are useless when we are not able to click those list items. So below code snippet will let you handle click events in listView so that you could be able to use it in your projects.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        String selectedItem=arrayList.get(position);
        Toast.makeText(getApplicationContext(), "Person Selected : "+selectedItem,   Toast.LENGTH_LONG).show();
    }
});

Place this code snippet in MainActivity.java inside the onCreate()methd.

Let me explain whats happening in the MainActivity.java.
So, we instantiated ArrayList of type String and named it as arrayList and then added the items in it.

Then we created a ListView and ArrayAdapter which taken in as String and named it as arrayAdapter and we set the adapter to listView by listView.setAdapter()method.

To handle click events in our listView, we used the onItemClickListener and said it what we want to do when a user clicks on any item. In this case we toast the items upon click.


In this post, you learnt about how to create a listView and use it to populate list items in it by using ArrayAdapters. The ArrayAdapter in this tutorial uses a string type and not custom implementation and also the ArrayAdapter uses Android Studio’s default (provided layout of simple_list_item_1) adapter. So if you want to learn more about how to implement a CustomAdapter then check it out at our website
https://blog.hiewpoint.com/category/android/