How to Create Custom ListView in Android using BaseAdapter || Custom List in Android || Custom ListView in Android - Android Tutorial World

Latest

Welcome to Android Tutorial World Blog, Here you can find all type of post or tutorial related to andorid app development in details.

Sunday, September 29, 2019

How to Create Custom ListView in Android using BaseAdapter || Custom List in Android || Custom ListView in Android

How to Create Custom ListView in Android


Hello Friends, Today we will teach you how to create custom ListView in Android.

Friends when we use listview its show a normal list but when we need to show attractive list in our project like :- List with title and description , List with Image , List with Button.
Then we need to create a custom list.

So Friends follow the steps for create custom listview in Android.

Step 1. Create a ListView in xml file.

<?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"/>

</RelativeLayout>

Code Image :-

Step 2. Now We need to create a custom layout for our listview.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:id="@+id/list_image"
        android:src="@drawable/ic_launcher_background"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_title"
        android:text="List Title"
        android:layout_toRightOf="@+id/list_image"
        android:layout_margin="10dp"/gt;

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_des"
        android:text="List Description"
        android:layout_below="@+id/list_title"
        android:layout_toRightOf="@+id/list_image"
        android:layout_marginLeft="10dp"/>

</RelativeLayout>

Code Image :-

If you don't know how to create layout file then follow the step.

First right click on layout folder


Now Right click on new option

Now click on Layout resource file

Now provide name of your layout file and click on ok

Now open this layout file from layout folder and make your list design according to your requirement / copy above code.

Step 3. Now We need to Create model class RowItem.

This model class contains two String type values for Title and Description and one int type value for displaying images in listitems.

Now click on java folder and select first package name of your project then right click on it and select new, now click on java class option.

Now create two String for list title and list description and one int for image.

Now Create Constructor ( Press :- alt + insert key ) for our java file

Now Select all

Now Create Getter and Setter ( Press :- alt + insert key )

Now Select All


Now Finally we need to override String method for showing position with name ( Text ).
So Now Override a String method ( Press :- ctrl + o key ).

Now we need to change return like :-

Full code :-

package com.akshayarora.myapplication;

import androidx.annotation.NonNull;

public class RowItem {
    private int imageId;
    private String title;
    private String desc;

    public RowItem(int imageId, String title, String desc) {
        this.imageId = imageId;
        this.title = title;
        this.desc = desc;
    }
    public int getImageId() {
        return imageId;
    }
    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }

    @NonNull
    @Override
    public String toString() {
        return title + "\n" + desc;
    }
}

Code Image :-

Step 4. Now We need to create Custom Adapter and extends with BaseAdapter Class.

CustomAdapter.java :-


package com.akshayarora.myapplication;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class CustomAdapter extends BaseAdapter {
    Context context;
    List<RowItem> rowItems;

    public CustomAdapter(Context context, List rowItems) {
        this.context = context;
        this.rowItems = rowItems;
    }
    private class ViewHolder{
        ImageView imageView;
        TextView txtTitle;
        TextView txtDescription;
    }
    @Override
    public int getCount() {
        return rowItems.size();
    }
    @Override
    public Object getItem(int i) {
        return rowItems.get(i);
    }
    @Override
    public long getItemId(int i) {
        return rowItems.indexOf(getItem(i));
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (view == null){
            view = inflater.inflate(R.layout.custom_list_style,null);
            holder = new ViewHolder();
            holder.imageView = (ImageView)view.findViewById(R.id.list_image);
            holder.txtTitle = (TextView)view.findViewById(R.id.list_title);
            holder.txtDescription = (TextView)view.findViewById(R.id.list_des);
            view.setTag(holder);
        }else {
            holder = (ViewHolder) view.getTag();
        }
        RowItem rowItem = (RowItem)getItem(i);
        holder.imageView.setImageResource(rowItem.getImageId());
        holder.txtTitle.setText(rowItem.getTitle());
        holder.txtDescription.setText(rowItem.getDesc());
        return view;
    }
}

Step 5. Now we need some Images for showing images in listview and we need to write some codes in our MainActivity.java Class

MainActivity.java :-
package com.akshayarora.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ListView listView;
    List<Rowitem> rowItems;
    CustomAdapter adapter;
    String[] country = new String[]{"India", "USA", "UK", "Japan"};
    String[] countryDes = new String[]{"India's Description","USA's Description","UK's Description","Japan's Description"};
    int[] img = new int[] {R.drawable.india,R.drawable.usa,R.drawable.uk,R.drawable.japan};

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

        rowItems = new ArrayList<RowItem>();
        for (int i = 0; i < country.length; i++){
            RowItem item = new RowItem(img[i],country[i],countryDes[i]);
            rowItems.add(item);
        }

        listView = (ListView)findViewById(R.id.listView);
        adapter = new CustomAdapter(this,rowItems);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(),"Item " + (i + 1) + ": " + rowItems.get(i),Toast.LENGTH_SHORT).show();
            }
        });

    }
}

Code Image :-

Now Run the project and see the output






Enjoy !

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.