Custom ListView Item in Java Android

Custom ListView Item in Java Android

Hi everyone, we are going to talk about how can we create our custom Listview in android with Java. We will build our own ListIems in XML and integrate it to ListView.

Firstly I want to talk about what ListView is
Android ListView is a view that groups various items and displays them in a vertically scrollable list. List items are automatically added to the list using an Adapter that pulls content from a source, such as an array or database.

An adapter bridges the interface components and the data source that fills the data into the interface Components. The adapter store and sends the data to the ListView component.

Now lets start to build our own Custom Listview Item.

I generally design the XML UI of these type of views. So now I will design the UI of ListView Item firstly.

Here is the my design :


<?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"
    android:background="@color/feed_bg"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"

        android:layout_marginLeft="@dimen/feed_item_margin"
        android:layout_marginRight="@dimen/feed_item_margin"
        android:layout_marginTop="@dimen/feed_item_margin"
        android:background="@drawable/bg_parent_rounded_corner"
        android:orientation="vertical"
        android:paddingBottom="@dimen/feed_item_padding_top_bottom"
        android:paddingTop="@dimen/feed_item_padding_top_bottom" >

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_height="200dp"
            android:padding="10dp">

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/feedImage1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/white"
                android:scaleType="fitXY" />


        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="@dimen/feed_item_padding_left_right"
            android:paddingRight="@dimen/feed_item_padding_left_right" >


            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="@dimen/feed_item_profile_info_padd" >

                <TextView
                    android:id="@+id/lblCatTitle"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/feed_item_profile_name"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/lblCatCount"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/timestamp"
                    android:textSize="@dimen/feed_item_timestamp" />
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

In this ListItem I have a NetworkImageView provided by Volley Library and TextViews. I will show the content Image with NetworkImageView. Also I will show the name and content counter with the text views. I will send the datas of these items from the Java My custom Java class.

Also I need to insert a ListView to the activity to show these items.


    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5dp"
        android:orientation="vertical">

        <ListView
            android:id="@+id/lstContentList"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center_horizontal"
            android:divider="@color/ContentBack"
            android:dividerHeight="0dp"
            android:footerDividersEnabled="false"
            android:headerDividersEnabled="false"
            android:paddingBottom="10dp"
            android:scrollbars="none" />
    </LinearLayout>

After created XML designs for user interfaces now we are ready to ceate our java class. First I will share the code and then I will explain what the code does.



import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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


public class ContentActivity extends AppCompatActivity {

    ArrayList<String> content_title_list;
    ArrayList<String> content_id_list;
    ArrayList<String> content_image_list;
    ArrayList<String> content_content_list;
    ArrayList<String> content_fav_list;
    ArrayList<String> content_read_list;
    ArrayList<String> content_favlayan_list;
    ArrayList<String> content_okuyan_list;

    Context context;

    ListView lstContentList ;
    private Activity activity;

    EditText txtSearch ;
    LinearLayout lnr_search ;

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private String shared_id_is_logged_in = "is_logged_in";
    private String shared_id_user_email = "user_email";
    private String shared_id_user_id = "user_id";
    private String shared_id_session_key = "session_key";

    String is_logged_in = "";
    String user_email = "";
    String user_id = "";
    String session_key = "";

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

        lstContentList = (ListView)findViewById(R.id.lstContentList);

        content_title_list = getIntent().getStringArrayListExtra("content_title_list");
        content_id_list = getIntent().getStringArrayListExtra("content_id_list");
        content_image_list = getIntent().getStringArrayListExtra("content_image_list");
        content_content_list = getIntent().getStringArrayListExtra("content_content_list");
        content_fav_list = getIntent().getStringArrayListExtra("content_fav_list");
        content_read_list = getIntent().getStringArrayListExtra("content_read_list");
        content_favlayan_list = getIntent().getStringArrayListExtra("content_favlayan_list");
        content_okuyan_list = getIntent().getStringArrayListExtra("content_okuyan_list");

        MyCatListAdapter adapter=new MyCatListAdapter(ContentActivity.this,R.layout.list_item_contents,content_title_list);
        lstContentList.setAdapter(adapter);

        lstContentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            private int selected_position = 0;

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selected_position = position;
            }
        });

    }

    private class MyCatListAdapter extends ArrayAdapter<String> {
        public MyCatListAdapter(Context context,int textViewResourceId,ArrayList<String> xmlList)
        {
            super(context, textViewResourceId, xmlList);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View row = convertView;
            if (row == null) {
                LayoutInflater inflater = ContentActivity.this.getLayoutInflater();
                row = inflater.inflate(R.layout.list_item_contents, parent, false);
            }
            TextView CatTitle = (TextView) row.findViewById(R.id.lblCatTitle);
            TextView CatContent = (TextView)row.findViewById(R.id.lblContent_desc);
            TextView CatMakaleStatu = (TextView)row.findViewById(R.id.lblMakaleStatu);
            TextView lblFavlayanCount = (TextView)row.findViewById(R.id.lblFavlayanSay);
            TextView lblOkuyanCount = (TextView)row.findViewById(R.id.lblOkuyanSay);

CatTitle.setText(content_title_list.get(position).replace("\\","\""));
            CatContent.setText(content_content_list.get(position).replace("\\","\""));

            lblFavlayanCount.setText(content_favlayan_list.get(position));
            lblOkuyanCount.setText(content_okuyan_list.get(position));

            if(content_read_list.get(position).equals("1")) CatMakaleStatu.setText("Read ");
            if(content_fav_list.get(position).equals("1")) CatMakaleStatu.setText("Favourites");
            if(content_read_list.get(position).equals("1") && content_fav_list.get(position).equals("1")) CatMakaleStatu.setText("Read and Favourited");

            mRequestQueue = Volley.newRequestQueue(ContentActivity.this);
            mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
                public void putBitmap(String bitmap_url, Bitmap bitmap) {
                    mCache.put(bitmap_url, bitmap);
                }
                public Bitmap getBitmap(String bitmap_url) {
                    return mCache.get(bitmap_url);
                }
            });

            NetworkImageView CatImage = (NetworkImageView)row.findViewById(R.id.feedImage1);
            CatImage.setImageUrl(content_image_list.get(position),mImageLoader);

            return row;
        }

    }

}

Now lets start to explain what we have done.

First we created some ArrayLists to use in our listview.


ArrayList<String> content_title_list;
ArrayList<String> content_id_list;
ArrayList<String> content_image_list;
ArrayList<String> content_content_list;
ArrayList<String> content_fav_list;
ArrayList<String> content_read_list;
ArrayList<String> content_favlayan_list;
ArrayList<String> content_okuyan_list;

In onCreate section we filled them from the data received from last activity with putStringArrayListExtra and getStringArrayListExtra. Below code block shows how to get ArrayLists from the last activity. I do not need to initialize before this. We are already initializing while declaring these array lists. Now our datas of listview is ready to use.


content_title_list = getIntent().getStringArrayListExtra("content_title_list");
        content_id_list = getIntent().getStringArrayListExtra("content_id_list");
        content_image_list = getIntent().getStringArrayListExtra("content_image_list");
        content_content_list = getIntent().getStringArrayListExtra("content_content_list");
        content_fav_list = getIntent().getStringArrayListExtra("content_fav_list");
        content_read_list = getIntent().getStringArrayListExtra("content_read_list");
        content_favlayan_list = getIntent().getStringArrayListExtra("content_favlayan_list");
        content_okuyan_list = getIntent().getStringArrayListExtra("content_okuyan_list");

Since our datas are ready now we have to call our Custom DataAdapter and load datas into it. After loaded datas we will bound this adapter and ListView in activity. Below code block is doing what I explained :


MyCatListAdapter adapter=new MyCatListAdapter(ContentActivity.this,R.layout.list_item_contents,content_title_list);
        lstContentList.setAdapter(adapter);

I have sended just one array. Make sure the all arrays have same quantity items. If it does not program will have NullPointer Exception. Also make sure an item has the datas in same indexes in arrays. Let me explain what I tried to tell.

If you are using seperate ArrayLists like this, all contents informations need to be same locations in all arrays in this method.

With another method: we can send the datas in One ArrayList as serialized.

Both of methods has one important state. We must be careful of data Serialization.

Now you know how to make your own listview custom items. You can create very colorful items and can show your featured datas in your listview directly.

It was the end of the article.

Keep following my articles.

Have a nice coding.

Burak Hamdi TUFAN...


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...