{"id":752,"date":"2016-01-31T07:28:07","date_gmt":"2016-01-31T07:28:07","guid":{"rendered":"http:\/\/abhiandroid.com\/ui\/?p=752"},"modified":"2019-06-12T13:08:01","modified_gmt":"2019-06-12T13:08:01","slug":"custom-simpleadapter","status":"publish","type":"post","link":"https:\/\/abhiandroid.com\/ui\/custom-simpleadapter.html","title":{"rendered":"Custom SimpleAdapter Tutorial With Example In Android Studio"},"content":{"rendered":"<p>Whenever we have to create a custom list we need to implement custom adapter. As we discuss earlier <a href=\"\/ui\/arrayadapter-tutorial-example.html\">ArrayAdapter<\/a> is used when we have a list of single item\u2019s backed by an Array. So if we need customization in a <a href=\"\/ui\/listview\">ListView<\/a> or a <a href=\"\/ui\/gridview\">GridView<\/a> we need to implement simpleadapter but when we need even more customization in list or grid items where we have many view\u2019s in a list item and also we have to perform any event like click or any other event to a particular view then we need to implement a custom adapter which fulfills our requirement. It is quite easy to implement.<\/p>\n<p>Before moving further, it is important to do quick revision of <a href=\"\/ui\/simpleadapter.html\">Android SimpleAdapter<\/a> which is an easy adapter to map static data to views defined in an XML file(layout). In android you can specify the data backing to a list as an ArrayList of Maps(hashmap or other). Each entry in an ArrayList is corresponding to one row of a list. The Maps contains \u00a0the data for each row. You also specify an XML file(custom list items file) that defines the views used to display the row, and a mapping from keys in the Map to specific views.<\/p>\n<p><span style=\"color: #ff0000;\"><strong>Important Note: <\/strong><\/span>We can\u2019t perform events like click and other event on child item of a list or grid but if we have some requirements to do that then we can create our own custom adapter and extends the simpleadapter in that.<\/p>\n<hr \/>\n<h4><strong>Custom SimpleAdapter<\/strong><\/h4>\n<p><a href=\"\/ui\/baseadapter-tutorial-example.html\">BaseAdapter<\/a> is the parent adapter for all other adapters so if we extends a SimpleAdapter then we can override the base adapter\u2019s function in that class.<\/p>\n<p><strong>Android CustomAdapter code when we extends SimpleAdapter in that:<\/strong><\/p>\n<pre>public class CustomAdapter extends SimpleAdapter {\r\npublic CustomAdapter(Context context, List&lt;? extends Map&lt;String, ?&gt;&gt; data, int resource, String[] from, int[] to) {\r\nsuper(context, data, resource, from, to);\r\n\r\n}\r\n\r\n@Override\r\npublic View getView(int position, View convertView, ViewGroup parent) {\r\nreturn super.getView(position, convertView, parent);\r\n\r\n}\r\n\r\n@Override\r\npublic int getCount() {\r\nreturn super.getCount();\r\n}\r\n}\r\n\r\n<\/pre>\n<p>In above code snippet we override functions of SimpleAdapter which are used to set the data in a list, grid or a spinner. There are few more methods but we mainly use these two method getCount() and getView().<\/p>\n<p><strong> 1. getCount():<\/strong><\/p>\n<p>The getCount() function returns the total number of items to be displayed in a list. It counts the value from arraylist size or an array\u2019s length. For example if we have a list of elements in a array list and we want to display the items in a listview then we can count the total number of those elements using the size function and that integer value is returned by the function getCount() as shown below.<\/p>\n<pre>@Override\r\npublic int getCount() {\r\n\r\nint count=arrayList.size(); \/\/counts the total number of elements from the arrayList.\r\nreturn count;\/\/returns the total count to adapter\r\n}<\/pre>\n<p><strong> 2. getView(<\/strong><strong>int <\/strong><strong>i, View view, ViewGroup viewGroup):<\/strong><\/p>\n<p>This function is automatically called when the list item view is ready to be display or about to be display. In this function we set the layout for list items from the second parameter of this function i.e view.<\/p>\n<p>Below is the getView function\u2019s example code with explanation included. Here we set the layout and then perform the click event on a image view from that layout.<\/p>\n<pre>@Override\r\npublic View getView(int i, View view, ViewGroup viewGroup) {\r\n\r\nView view=super.getView(position, convertView, parent);\r\nImageView imageView=(ImageView) view.findViewById(R.id.<em>imageView<\/em>);\r\nimageView.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View view) {\r\nToast.<em>makeText<\/em>(context, arrayList.get(position).get(\"name\"), Toast.<em>LENGTH_SHORT<\/em>).show();\r\n}\r\n});\r\nreturn view;\r\n}<\/pre>\n<hr \/>\n<h4><strong>Example Of Custom SimpleAdapter in Android Studio:<\/strong><\/h4>\n<p>In the below example of custom simple adapter we display the custom list of fruit names with their images in a list view where fruit image is displayed in the left side of the screen and the name is displayed to the right side of the image. When we click on a fruit image the name of the fruit is displayed.<\/p>\n<p style=\"text-align: center;\"><a class=\"download\" href=\"https:\/\/github.com\/abhisheksaini4\/customSimpleAdapterExample\" target=\"_blank\" rel=\"nofollow\">Download Code<\/a><a class=\"help\" title=\"Learn How To Download Code And Import In Android Studio\" href=\"\/androidstudio\/download-code-abhiandroid\" target=\"_blank\" rel=\"nofollow\"> ? <\/a><\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-755\" src=\"\/ui\/wp-content\/uploads\/2016\/01\/Custom-SimpleAdapter-Example-In-Android-Studio.jpg\" alt=\"Custom SimpleAdapter Example In Android Studio\" width=\"261\" height=\"452\" srcset=\"https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/01\/Custom-SimpleAdapter-Example-In-Android-Studio.jpg 261w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/01\/Custom-SimpleAdapter-Example-In-Android-Studio-173x300.jpg 173w\" sizes=\"auto, (max-width: 261px) 100vw, 261px\" \/><\/center><span style=\"color: #008000;\"><strong>Step 1:<\/strong><\/span> Create a new project in Android Studio and name it CustomSimpleAdapterExample.<\/p>\n<pre>Select File -&gt; New -&gt; New Project and Fill the forms and click \"Finish\" button.\r\n<\/pre>\n<p>Step 2: Open app\u00a0 -&gt; res -&gt; layout -&gt;\u00a0<strong>xml (or) activity_main.xml<\/strong>\u00a0and add following code. Here we are creating ListView inside RelativeLayout.<\/p>\n<pre>&lt;RelativeLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\nxmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"match_parent\"\r\ntools:context=\".MainActivity\"&gt;\r\n\r\n&lt;ListView\r\nandroid:id=\"@+id\/simpleListView\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:divider=\"#000\"\r\nandroid:dividerHeight=\"2dp\" \/&gt;\r\n\r\n&lt;\/RelativeLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 3:<\/strong><\/span> Now Create new a new layout Activity. Go to <strong>res-&gt; right click on layout -&gt; New -&gt; Activity -&gt; Blank Activity and create list_view_items.xml <\/strong>and add following code. Here we are creating items view that will be displayed inside each row.<\/p>\n<pre>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\nandroid:layout_width=\"match_parent\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:background=\"#fff\"&gt;\r\n\r\n&lt;ImageView\r\nandroid:id=\"@+id\/imageView\"\r\nandroid:layout_width=\"60dp\"\r\nandroid:layout_height=\"60dp\"\r\nandroid:layout_marginLeft=\"10dp\"\r\nandroid:padding=\"5dp\"\r\nandroid:src=\"@drawable\/ic_launcher\" \/&gt;\r\n\r\n&lt;TextView\r\nandroid:id=\"@+id\/textView\"\r\nandroid:layout_width=\"wrap_content\"\r\nandroid:layout_height=\"wrap_content\"\r\nandroid:layout_gravity=\"center\"\r\nandroid:padding=\"@dimen\/activity_horizontal_margin\"\r\nandroid:text=\"Demo\"\r\nandroid:textColor=\"#000\" \/&gt;\r\n&lt;\/LinearLayout&gt;\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 4:<\/strong><\/span> Now open app -&gt; java -&gt; package -&gt;\u00a0MainActivity.java and add the following code. Explanation is added in the code itself:<strong><br \/>\n<\/strong><\/p>\n<pre>package example.abhiandriod.customsimpleadapterexample;\r\n\r\nimport android.support.v7.app.AppCompatActivity;\r\nimport android.os.Bundle;\r\nimport android.view.Menu;\r\nimport android.view.MenuItem;\r\nimport android.view.View;\r\nimport android.widget.AdapterView;\r\nimport android.widget.ListView;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\n\r\npublic class MainActivity extends AppCompatActivity {\r\n\r\n    \/\/initialize view's\r\n    ListView simpleListView;\r\n    String[] fruitsNames = {\"Apple\", \"Banana\", \"Litchi\", \"Mango\", \"PineApple\"};\/\/fruit names array\r\n    int[] fruitsImages = {R.drawable.apple, R.drawable.banana, R.drawable.litchi, R.drawable.mango, R.drawable.pineapple};\/\/fruits images array\r\n\r\n    @Override\r\n    protected void onCreate(Bundle savedInstanceState) {\r\n        super.onCreate(savedInstanceState);\r\n        setContentView(R.layout.activity_main);\r\n        simpleListView = (ListView) findViewById(R.id.simpleListView);\r\n\r\n        ArrayList&lt;HashMap&lt;String, String&gt;&gt; arrayList = new ArrayList&lt;&gt;();\r\n        for (int i = 0; i &lt; fruitsNames.length; i++) {\r\n            HashMap&lt;String, String&gt; hashMap = new HashMap&lt;&gt;();\/\/create a hashmap to store the data in key value pair\r\n            hashMap.put(\"name\", fruitsNames[i]);\r\n            hashMap.put(\"image\", fruitsImages[i] + \"\");\r\n            arrayList.add(hashMap);\/\/add the hashmap into arrayList\r\n        }\r\n        String[] from = {\"name\", \"image\"};\/\/string array\r\n        int[] to = {R.id.textView, R.id.imageView};\/\/int array of views id's\r\n        CustomAdapter simpleAdapter = new CustomAdapter(this, arrayList, R.layout.list_view_items, from, to);\/\/Create object and set the parameters for simpleAdapter\r\n        simpleListView.setAdapter(simpleAdapter);\/\/sets the adapter for listView\r\n\r\n        \/\/perform listView item click event\r\n        simpleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {\r\n            @Override\r\n            public void onItemClick(AdapterView&lt;?&gt; adapterView, View view, int i, long l) {\r\n                Toast.makeText(getApplicationContext(), fruitsNames[i], Toast.LENGTH_LONG).show();\/\/show the selected image in toast according to position\r\n            }\r\n        });\r\n\r\n    }\r\n    \r\n}<\/pre>\n<p><span style=\"color: #008000;\"><strong>Step 5:<\/strong><\/span> Now create New Class. Go to app -&gt; java -&gt; right click on package-&gt; New -&gt; Java Class and create CustomAdapter.java and add following code. Here we extends SimpleAdapter in CustomAdapter class and override the methods of BaseAdapter since it is the parent adapter for all other adapters.<\/p>\n<pre>package example.abhiandriod.customsimpleadapterexample;\r\n\r\nimport android.content.Context;\r\nimport android.view.LayoutInflater;\r\nimport android.view.View;\r\nimport android.view.ViewGroup;\r\nimport android.widget.ImageView;\r\nimport android.widget.SimpleAdapter;\r\nimport android.widget.Toast;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\n\r\npublic class CustomAdapter extends SimpleAdapter {\r\nLayoutInflater inflater;\r\nContext context;\r\nArrayList&lt;HashMap&lt;String, String&gt;&gt; arrayList;\r\n\r\npublic CustomAdapter(Context context, ArrayList&lt;HashMap&lt;String, String&gt;&gt; data, int resource, String[] from, int[] to) {\r\nsuper(context, data, resource, from, to);\r\nthis.context = context;\r\nthis.arrayList = data;\r\ninflater.<em>from<\/em>(context);\r\n}\r\n\r\n@Override\r\npublic View getView(final int position, View convertView, ViewGroup parent) {\r\nView view = super.getView(position, convertView, parent);\r\nImageView imageView = (ImageView) view.findViewById(R.id.<em>imageView<\/em>);\r\nimageView.setOnClickListener(new View.OnClickListener() {\r\n@Override\r\npublic void onClick(View view) {\r\nToast.<em>makeText<\/em>(context, arrayList.get(position).get(\"name\"), Toast.<em>LENGTH_SHORT<\/em>).show();\r\n}\r\n});\r\nreturn view;\r\n}\r\n\r\n}\r\n<\/pre>\n<p><span style=\"color: #008000;\"><strong>Output:<\/strong><\/span><\/p>\n<p>Now start AVD in Emulator and run the App. You will see the custom list of fruit names with their images in a list view. Click on any fruit to see its name displayed on screen as Toast message.<\/p>\n<p><center><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-756\" src=\"\/ui\/wp-content\/uploads\/2016\/01\/Custom-SimpleAdapter-Example-Output.jpg\" alt=\"Custom SimpleAdapter Example Output\" width=\"290\" height=\"454\" srcset=\"https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/01\/Custom-SimpleAdapter-Example-Output.jpg 290w, https:\/\/abhiandroid.com\/ui\/wp-content\/uploads\/2016\/01\/Custom-SimpleAdapter-Example-Output-192x300.jpg 192w\" sizes=\"auto, (max-width: 290px) 100vw, 290px\" \/><\/center><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Whenever we have to create a custom list we need to implement custom adapter. As we discuss earlier ArrayAdapter is used when we have a list of single item\u2019s backed by an Array. So if we need customization in a ListView or a GridView we need to implement simpleadapter but when we need even more &hellip; <a href=\"https:\/\/abhiandroid.com\/ui\/custom-simpleadapter.html\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Custom SimpleAdapter Tutorial With Example In Android Studio<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":755,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[62,1],"tags":[],"class_list":["post-752","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-adapter","category-archieve"],"acf":[],"psp_head":"<title>Custom SimpleAdapter Tutorial With Example In Android Studio \u2013 Abhi Android<\/title>\r\n<meta name=\"description\" content=\"Whenever we have to create a custom list we need to implement custom adapter. Find its tutorial with example in Android Studio. Also details about getCount() and getView() two methods which we override for Custom SimpleAdapter.\" \/>\r\n<meta name=\"robots\" content=\"index,follow\" \/>\r\n<link rel=\"canonical\" href=\"https:\/\/abhiandroid.com\/ui\/custom-simpleadapter.html\" \/>\r\n","_links":{"self":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts\/752","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/comments?post=752"}],"version-history":[{"count":3,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts\/752\/revisions"}],"predecessor-version":[{"id":2834,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/posts\/752\/revisions\/2834"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/media\/755"}],"wp:attachment":[{"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/media?parent=752"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/categories?post=752"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/abhiandroid.com\/ui\/wp-json\/wp\/v2\/tags?post=752"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}