Android Custom ViewList with onItemClickListener

Android Custom ViewList with onItemClickListener

If you want to create a custom List you have to implement BaseAdapter (Observable pattern) making modifications with a help of getView() method  .

BaseAdapter is a common based class providing an Adapter an implemantation.Generally you use it in Listview and SpinnerAdapter.The most important method is notifyDataSetChanged().The method refresh the modifications of the View.A View is a child of an Adapter class and provides UI interface with Layout and properties.

In general a simple listview item consists only a Textview and optional overloaded parameter for the “check box”(Android.Resource.Layout.SimpleListItemChecked).In reality you need more complex list like deleting items from list or inserting new items to a list and refresh it to a current state.The main purpose of getView is to initialize components (Buttons,Textview..) and provide it with data.

The are 2 ways to make it work.The first way is just to inflate our XML file and the other is making own Inflator.

In this example we ovveride our getView() and  inflate our listview_new because we want to make a:

ImageButton 

Button for deleting each element.

Textview (show price)

Textview (name of the recipe)

First, create a Listviewadapter class.

package learn.hq.customviewlist;

import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class listviewadapter extends BaseAdapter  {
int positionItem;
    public ArrayList<Recipe> recipeList;
    Activity activity;
    ListView lv;
    private int position;
    private View.OnClickListener listener;

    public listviewadapter(Activity activity, ArrayList<Recipe> recipeList) {
        super();
        this.activity = activity;
        this.recipeList = recipeList;

    }


    @Override
    public int getCount() {
        return recipeList.size();
    }

    @Override
    public Object getItem(int position) {
        return recipeList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ViewHolder {
        TextView price;
        ImageButton imagedel;
        ImageButton btnimag;
        TextView recipedesc;
        TextView level;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listview_new, null);
            holder = new ViewHolder();
            holder.imagedel = (ImageButton) convertView.findViewById(R.id.imagdel);
            holder.btnimag = (ImageButton) convertView.findViewById(R.id.btnImage);
            holder.price = (TextView) convertView.findViewById(R.id.price);
            holder.recipedesc = (TextView) convertView
                    .findViewById(R.id.Recipedesc);
            holder.level = (TextView) convertView.findViewById(R.id.level);

            convertView.setTag(holder);
            convertView.setScrollBarSize(5);
            holder.btnimag.setTag(recipeList.get(position));
            positionItem = position;



        } else {
            holder = (ViewHolder) convertView.getTag();

        }


        Recipe item = recipeList.get(position);

        holder.price.setText(item.getPrice() + "$");

        holder.recipedesc.setText(item.getName().toString());
        holder.imagedel.setImageResource(R.drawable.ic_clear_black_24dp);
        holder.btnimag.setImageResource(item.getImg());
        holder.level.setText(item.getLevel());

holder.imagedel.setTag(position);
        // holder.mCategory.setText(item.getCategory().toString());
        //holder.mPrice.setText(item.getPrice().toString());
        holder.imagedel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos = (int)v.getTag();

                Log.i("asd",v.getTag()+" ");
                recipeList.remove(pos);
                notifyDataSetChanged();
            }
        });
        return convertView;
    }


    public void removeView(Object position) {
        // lv and the adapter must be public-static in their Activity Class
     recipeList.remove(Integer.parseInt(position.toString()));

    }
}

Second, we need our Model: we create Recipe class with getter and setter methods.

package learn.hq.customviewlist;

import android.media.Image;

public class Recipe {
    private String name;
private String level;
private int price;
private int img;

Recipe(String name,String level,int price,int img){
    this.name  = name;
    this.level = level;
    this.price = price;
    this.img = img;
}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLevel() {
        return level;
    }

    public int getPrice() {
        return price;
    }


    public int getImg() {
        return img;
    }

    public void setImg(int img) {
        this.img = img;
    }
}

MainActivity 

package learn.hq.customviewlist;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ListView lview;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);
        final ArrayList<Recipe> recipeList = new ArrayList<Recipe>();


        recipeList.add(new Recipe("Pork","EASY",5,R.drawable.pork));

        recipeList.add(new Recipe("Salat","MEDIUM",5,R.drawable.salat2));

        recipeList.add(new Recipe("Risoto","MEDIUM",2,R.drawable.risoto));

        recipeList.add(new Recipe("Pork","EASY",5,R.drawable.pork));

        recipeList.add(new Recipe("Salat","MEDIUM",5,R.drawable.salat2));

        recipeList.add(new Recipe("Risoto","MEDIUM",2,R.drawable.risoto));

        //recipeList.add(new Recipe("groundpork","MEDIUM",5,R.drawable.groundpork));


lview = (ListView) findViewById(R.id.listrecipe);
listviewadapter adapter = new listviewadapter(this, recipeList);
lview.setAdapter(adapter);


    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/listrecipe"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

listview_new.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

    <ImageButton
        android:id="@+id/btnImage"
        android:layout_width="84dp"
        android:layout_height="81dp"
        android:background="@android:drawable/screen_background_light_transparent"
        tools:src="@android:color/transparent"
        tools:srcCompat="@android:color/transparent" />

    <ImageButton
        android:id="@+id/imagdel"
        android:layout_width="88dp"
        android:layout_height="87dp"
        android:translationX="150dp"
        android:translationY="0dp"
        app:srcCompat="@drawable/ic_clear_black_24dp" />

    <TextView
        android:id="@+id/Recipedesc"
        android:layout_width="41dp"
        android:layout_height="wrap_content"
        android:translationX="-80dp"
        android:translationY="20dp"
        tools:text="price" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Header"
        android:translationX="-120dp" />

    <TextView
        android:id="@+id/level"
        android:layout_width="91dp"
        android:layout_height="32dp"
        android:layout_weight="1"
        android:text="TextView"
        android:translationX="-130dp"
        android:translationY="50dp" />


</LinearLayout>

Change Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="learn.hq.customviewlist">


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Result

Full Source Code:

One thought on “Android Custom ViewList with onItemClickListener”

  • Gennadiy Shevtsov

    Gennadiy Shevtsov says:

    Hey,

    Thank you guys for 1500 pageviews. I appreciate it.
    Don’t be shy just ask me if you have questions =))
    What other tutorials would you like to see? Please post your requests here.

    Best Regards
    Gennadiy Shevtsov

Leave a Reply

Your email address will not be published. Required fields are marked *