How to create a custom listview in android?

AndroidMobile DevelopmentProgramming

Before getting into listview example, we should know about listview, Listview is a collection of items pulled from arraylist, list or any databases. Most uses of listview is a collection of items in vertical format, we can scroll up/down and click on any item.

What is custom listview?

Custom listview works based on customAdapter. In this custom adapter we can pass custom object. We are passing subject data to listview as shown below −

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
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">
<LinearLayout
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical">
   <ListView
      android:id = "@+id/list"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent"
      android:divider = "#000"
      android:dividerHeight = "1dp"
      android:footerDividersEnabled = "false"
      android:headerDividersEnabled = "false"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

In the above activity_main.xml, we have declared a listview and added divider as shown below.

<ListView
   android:id = "@+id/list"
   android:layout_width = "wrap_content"
   android:layout_height = "match_parent"
   android:divider = "#000"
   android:dividerHeight = "1dp"
   android:footerDividersEnabled = "false"
   android:headerDividersEnabled = "false"
/>

Step 3 − Add the following code to src/MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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);
      final ListView list = findViewById(R.id.list);
      ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
      arrayList.add(new SubjectData("JAVA", "https://www.tutorialspoint.com/java/",             "https://www.tutorialspoint.com/java/images/java-mini-logo.jpg"));
      arrayList.add(new SubjectData("Python", "https://www.tutorialspoint.com/python/", "https://www.tutorialspoint.com/python/images/python-mini.jpg"));
      arrayList.add(new SubjectData("Javascript", "https://www.tutorialspoint.com/javascript/", "https://www.tutorialspoint.com/javascript/images/javascript-mini-logo.jpg"));
      arrayList.add(new SubjectData("Cprogramming", "https://www.tutorialspoint.com/cprogramming/", "https://www.tutorialspoint.com/cprogramming/images/c-mini-logo.jpg"));
      arrayList.add(new SubjectData("Cplusplus", "https://www.tutorialspoint.com/cplusplus/", "https://www.tutorialspoint.com/cplusplus/images/cpp-mini-logo.jpg"));
      arrayList.add(new SubjectData("Android", "https://www.tutorialspoint.com/android/", "https://www.tutorialspoint.com/android/images/android-mini-logo.jpg"));
      CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
      list.setAdapter(customAdapter);
   }
}

In the mainActivity, we have declared CustomAdapter and passed SubjectData as shown below −

CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);

Step 4 − Create a CustomAdapter class Add the following code to src/ CustomAdapter.java

import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
class CustomAdapter implements ListAdapter {
   ArrayList<SubjectData> arrayList;
   Context context;
   public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
      this.arrayList=arrayList;
      this.context=context;
   }
   @Override
   public boolean areAllItemsEnabled() {
      return false;
   }
   @Override
   public boolean isEnabled(int position) {
      return true;
   }
   @Override
   public void registerDataSetObserver(DataSetObserver observer) {
   }
   @Override
   public void unregisterDataSetObserver(DataSetObserver observer) {
   }
   @Override
   public int getCount() {
      return arrayList.size();
   }
   @Override
   public Object getItem(int position) {
      return position;
   }
   @Override
   public long getItemId(int position) {
      return position;
   }
   @Override
   public boolean hasStableIds() {
      return false;
   }
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      SubjectData subjectData=arrayList.get(position);
      if(convertView==null) {
         LayoutInflater layoutInflater = LayoutInflater.from(context);
         convertView=layoutInflater.inflate(R.layout.list_row, null);
         convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
         });
         TextView tittle=convertView.findViewById(R.id.title);
         ImageView imag=convertView.findViewById(R.id.list_image);
         tittle.setText(subjectData.SubjectName);
         Picasso.with(context)
         .load(subjectData.Image)
         .into(imag);
      }
      return convertView;
   }
   @Override
   public int getItemViewType(int position) {
      return position;
   }
   @Override
   public int getViewTypeCount() {
      return arrayList.size();
   }
   @Override
   public boolean isEmpty() {
      return false;
   }
}

Step 5 − Create a SubjectData class, Add the following code to src/ SubjectData.java

class SubjectData {
   String SubjectName;
   String Link;
   String Image;
   public SubjectData(String subjectName, String link, String image) {
      this.SubjectName = subjectName;
      this.Link = link;
      this.Image = image;
   }
}

Step 6 − In the CustomAdapter class we have showed internet source image. To show internet source image. we have added picasso library as shown below.

Picasso.with(context)
.load(subjectData.Image)
.into(imag);

Step 7 − For picasso library implementation, we have to add picasso library in gradle as shown below

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.andy.myapplication"
      minSdkVersion 15
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }  
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   implementation 'com.squareup.picasso:picasso:2.5.1'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Step 8 − To access internet information, we have to give internet permission to manifest file as shown below.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
   <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>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Play Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

Default Output Screen

Click here to download the project code

raja
Published on 05-Dec-2018 12:29:52
Advertisements