Android listview with sections

Содержание
  1. ListView в Android: Кастомизация списков
  2. Пример: ListActivity с собственным шаблоном.
  3. Пример: ListActivity с гибким шаблоном
  4. Продвинутые ListActivity
  5. Мультивыбор
  6. Хедер и Футер
  7. SimpleCursorAdapter
  8. Android ListView Section Header Example Group By Header
  9. Last Views
  10. What is Section Header ?
  11. Step 1. Layout Resources
  12. Step 2. Separate Classes
  13. Step 3. Custom Adapter
  14. Step 4. Final Codes
  15. Diving Deep In Main Activity
  16. Understanding Adapter
  17. Android ListView With Header | Pinned header, Sticky, Section
  18. 1. Android ListView With Fixed Header And Footer Example
  19. Look Header And Footer
  20. Step 1. Separate Views
  21. Step 3. XML file For ListView
  22. Step 5. List Adapter
  23. Starring at adapter
  24. Step 6. Final Updates
  25. Noticing the above
  26. 2. Android ListView Sticky Header Like iphone | Pinned header listview
  27. Last Views For Header
  28. Step 1. Adding Colors
  29. Step 2. Adding Image
  30. Step 3. Preparing HeaderListView And Section Adapter Class
  31. Step 4. Ios Adapter
  32. Looking Deeply
  33. getRowView()
  34. Handling Click Events
  35. Step 5. Main Updates
  36. 3. Android Multi Column ListView With Sticky Header Example
  37. See Our MultiColumn ListView
  38. Step 1. Making a List Item File
  39. Step 2. Food Model
  40. Step 3. Food Adapter Class
  41. Diving Step by Step
  42. Step 4. Making Final Changes
  43. What does above code means ?
  44. 4. Android ListView Section Header Example Group By Header
  45. Last Views
  46. What is Section Header ?
  47. Step 1. Layout Resources
  48. Step 2. Separate Classes
  49. Step 3. Custom Adapter
  50. Step 4. Final Codes
  51. Diving Deep In Main Activity
  52. Understanding Adapter

ListView в Android: Кастомизация списков

Продолжение статьи о ListView в Android, в котором мы рассмотрим более сложные примеры его использования, такие, как иконки на элементах списка и добавление чекбоксов к этим элементам. Так же мы рассмотрим возможности по оптимизации кода.

Напомню, что статья является переводом этой статьи с разрешения ее автора.

Пример: ListActivity с собственным шаблоном.

Вы можете создать свой собственный шаблон для элементов списка и применить его к своему Адаптеру. Шаблон будет одинаковым для каждого элемента списка, но дальше мы разберем как сделать его более гибким. В нашем примере мы добавим иконку к каждому элементу списка.

Создайте файл шаблона «rowlayout.xml» в папке res/layout вашего проекта «de.vogella.android.listactivity».

Измените свою Деятельность на следующую. Код почти такой же, как и в предыдущем примере, единственная разница в том, что мы используем наш собственный шаблон в ArrayAdapter и указываем адаптеру какой элемент пользовательского интерфейса будет содержать текст. Мы не делали этого в предидущей статье, поскольку мы использовали стандартный шаблон.

Пример: ListActivity с гибким шаблоном

Оба предыдущих примера используют один шаблон сразу для всех строк. Если вы хотите изменить вид определенных строк, вам нужно определить свой адаптер и заместить метод getView().

Этот метод ответственен за создание отдельных элементов вашего ListView. getView() возвращает Вид. Этот Вид фактически является Шаблоном (ViewGroup) и содержит в себе другие Виды, например, ImageView или TextView. С getView() вы так же можете изменить параметры индивидуальных видов.

Чтобы прочитать шаблон из XML в getView(), вы можете использовать системный сервис LayoutInflator.

В этом примере мы расширяем ArrayAdapter, но так же мы можем реализовать непосредственно BaseAdapter.

Определение простого адаптера

Очень просто создать свой Адаптер, не обращая внимания на его оптимизацию. Просто получайте в своей Деятельности данные, которые хотите отобразить и сохраняйте их в элемент списка. В вашем getView() установите ваш предопределенный шаблон для элементов и получите нужные вам элементы с помощью findViewById(). После этого вы можете определить их свойства.

Наш пример использует две картинки: «no.png» и «ok.png». Я положил их в папку «res/drawable-mdpi». Используйте свои картинки. Если не нашли таковых, то просто скопируйте «icon.png» и, с помощью графического редактора, немного измените их.

Создайте класс «MySimpleArrayAdapter», который будет служить нашим Адаптером.

Чтобы использовать этот Адаптер, измените класс MyList на следующее

Когда вы запустите это приложение, вы увидите список с элементами, с разными значками на некоторых из них.

Оптимизация производительности вашего собственного адаптера

Создание Java объектов для каждого элемента — это увеличение потребления памяти и временные затраты. Как уже говорилось, Андроид стирает элементы (виды) вашего списка, которые уже не отображаются и делегируют управление ими в метод getView() через параметр convertView.

Ваш Адаптер может использовать этот вид и избежать «раздутие» Шаблона для этого элемента. Это сохраняет память и уменьшает загрузку процессора.

В вашей реализации вы должны проверять convertView на наличие содержимого и переназначать его, отправляя новые данные в существующий Шаблон, если convertView не пустой.

Наша реализация так же использует модель ViewHolder. Метод findViewById() достаточно ресурсоемок, так что нужно избегать его, если в нем нет прямой необходимости.

ViewHolder сохраняет ссылки на необходимые в элементе списка Шаблоны. Этот ViewHolder прикреплен к элементу методом setTag(). Каждый Вид может содержать примененную ссылку. Если элемент очищен, мы можем получить ViewHolder через метод getTag(). Это выглядит нагруженным, но, на самом деле, работает быстрее, чем повторяющиеся вызовы findViewById().

Обе техники (переназначение существующих видов и модель ViewHolder) увеличивают производительность примерно на 15%, особенно на больших объемах данных.

Продолжая использовать проект «de.vogella.android.listactivity», создайте класс «MyArrayAdapter.java».

Продвинутые ListActivity

Обработка долгого нажатия на элементе

Вы так же можете добавить LongItemClickListener к виду. Для этого получите ListView через метод getListView() и определите обработку длительного нажатия через метод setOnItemLongClickListener().

Элементы, взаимодействующие с моделью данных

Ваш шаблон элемента списка так же может содержать Виды, взаимодействующие с моделью данных. Например, вы можете использовать Checkbox в элементе списка и, если чекбокс включен, вы можете менять данные, отображаемые в элементе.

Мы до сих пор используем тот же проект. Создайте шаблон элемента списка «rowbuttonlayout.xml».

создайте для этого примера класс Model, который содержит название элемента и его содержимое, если он чекнут.

Создайте следующий Адаптер. Этот Адаптер добавит обработку изменения Checkbox. Если чекбокс включен, то данные в модели тоже меняются. Искомый Checkbox получает свою модель через метод setTag().

В завершение измените свой ListView на следующий.

Когда вы запустите ваше приложение, вам будет доступна отметка элементов, которая будет отражаться на вашей модели.

Мультивыбор

Так же можно сделать одиночный и мультивыбор. Посмотрите следующие сниппеты для примера. Чтобы получить выбранные элементы используйте listView.getCheckedItemPosition() или listView.getCheckedItemPositions(). Вы так же можете использовать listView.getCheckedItemIds(), чтобы получить ID выбранных элементов.

Хедер и Футер

Вы можете поместить произвольные элементы вокруг своего списка. Например, вы можете создать шаблон со списком между двумя TextView. Если вы так сделаете, то вы должны указать id «@android:id/list» к ListView, т.к. ListActivity ищет Вид с таким идентификатором. В таком случае один TextView всегда будет видимым над ListView (Хедер), а другой будет виден внизу. Если вы хотите использовать Футер и Хедер только в конце/начале списка, чтобы они не были фиксированными, то нужно использовать view.setHeaderView() или view.setFooterView(), например:

SimpleCursorAdapter

Если вы работаете с базой данных или же с контентом непосредственно, вы можете использовать SimpleCursorAdapter, чтобы перенести данные в ваш ListView.

Создайте новый проект «de.vogella.android.listactivity.cursor» с деятельностью «MyListActivity». Создайте такую деятельность.

Убедитесь, что вы дали приложению доступ к контактам. (Используйте «android.permission.READ_CONTACTS» в AndroidManifest.xml).

Спасибо за внимание. Комментарии и поправки к переводу приветствуются, т.к. даже в исходнике встречаются ошибки и опечатки.

Прошу прощения за репост, изначально не отметил как перевод, поскольку недавно здесь. Большое спасибо за наводку jeston, принял к сведению и научился на ошибках.

Источник

Android ListView Section Header Example Group By Header

I will explain about android listview section header with example in this article.

You will make a listview with a specific header between it’s row items.

Last Views

After all of this hard work, you should get the listview like below video

What is Section Header ?

Section header means that a header among listview items to sort them with particular category.

For example, you are making listview with county names. Now countries can be categorized by continents.

So, you will make the first row as a section header which have continent name like Asia. Then in the second, third row you will write Asian countries like India, Chine etc.

Читайте также:  Блютуз парктроники для андроид

After Asia, again you will make listview row as a section header and will name it Europe and further this process continues.

In this example, we will group listview by vehicle type as a header. We will create custom view for header which is different than the normal listview item.

So let us follow all the below steps carefully.

Step 1. Layout Resources

Different layout for header and normal rows requires different layout xml files. Hence, we will create two layout resources files.

Make two xml files res->layout directory.

Give a name lv_child.xml to first file and lv_header.xml to second xml file.

Add below code in lv_child.xml

Above file will create the layout for normal listview row items.

Copy following code in lv_header.xml

This code will generate the layout for header rows.

Step 2. Separate Classes

We need to create two java classes for both normal and header rows.

This class will work as a general model class. So make two new java classes and name them HeaderModel.java and ChildModel.java respectively.

Write down the below code in HeaderModel.java

isHeader() method will tell compiler whether the listview row is a header row or a normal row.

setheader(String header) method will set the string as a header title which passes as a parameter.

getName() method will return a header text in a string format.

Now add the below code in ChildModel.java

Similar methods are used here as HeaderModel.java class. Only difference is that get method will return normal row item text and set method will set the text as a row item name.

Step 3. Custom Adapter

As always, every listview requires an adapter class which will provide the data to populate the listview rows.

Make a new java class named CustomeAdapter.java and add below code in it.

Here I am populating listview with the help of the listItemArraylist.

listItemArraylist is created in the Main activity and passed as a parameter to the constructor of this adapter class.

Hence, let us first understand the Main Activity so it would be easier to understand adapter class.

Step 4. Final Codes

Now the final task is to write Main Activity code.

Add below code in activity_main.xml

Write the following code in MainActivity.java file

Diving Deep In Main Activity

Consider below code

First string array vehicleTypes will provide the header names.

Secong string array childnames will provide the text names for normal listview rows.

listItemArraylist is defined as below

Here ListItem is an Interface which in implemented by both model classes : HeaderModel.java and ChildModel.java.

So the methods present is the ListItem interface are overriden in HeaderModel.java and ChildModel.java.

Following is the code for the Interface ListItem

As we have seen earlier in Step 2 that both the methods of Interface ListItem are overriden in HeaderModel.java and ChildModel.java.

Now we will create data structure using populateList() method.

Below is the source code for the populateList() method.

Here I have make four child rows for each header.

Listview will start with the first header then four rows will be it’s child items. The fifth row will be second header and then four rows will be the child row for second header and it continues in this fashion.

So the first, sixth, eleventh and sixteenth row of the listview will be header rows.

Hence in the for loop if condition will be true for four times.

When the if condition is true, object of the HeaderModel will be added to the listIemArrayList

In all other for loop iterations, object of the ChildModel will be added to the listIemArrayList.

After completion of for loop, listIemArrayList is passed to the adapter constructor.

Now let’s see the adapter code.

Understanding Adapter

Read the below code for getView() method

This method will fetch the data from listIemArrayList and will populate the listview using that data.

Look at the following codes

It will check for the header object by using isHeader() method.

If isHeader() method returns true then compiler will inflate the lv_header.xml file as a listview row layout.

Otherwise it will inflate the lv_child.xml

After checking for above conditions and inflating the layout file compiler will set the text pf the listview row using the below line

Источник

Android ListView With Header | Pinned header, Sticky, Section

The article of today is about Android ListView With Header And Footer Example.

1. Android ListView With Fixed Header And Footer Example

We can add fixed header and footer to listview which are always visible.

Android have built in methods like addheaderview and addfooterview for ListView class.

We can use these methods to make custom header and footer for listview.

Header and Footer will always stick and visible at the start (Header) and end (Footer) of the listview.

Example of this tutorial can be the checkout or bill summary screen of any restaurant.

This checkout screen need the header and footer of the listview.

Here, different food items with their name,quantity and price are set in the listview because every order have different number of food items so it is not fix.

And, in the header of the listview, you need to fix the name and logo of the restaurant while in footer, you can show the total amount payable.

Having built in methods is great advantage and simplifies the whole process.

Step 1. Separate Views

We need to create separate views for header and footer in this example.

Separate views gives us better options for customization.

First of all create a new XML resource file named header_view.xml

Add the following coding lines in header_view.xml

I have taken only one textview in the header file.

You can add imageview to add image, button, videoview or any other UI widget as you like.

Customize this file with different colors and styles and images to make it more attractive or as per your client’s requirements.

Make another XML layout resource file in res->layout directory.

Name of this file should be footer_view.xml

Copy the below source code in footer_view.xml

This file will create the view for footer.

I have make it same as the header view with just one textview.

You can also customize this file with various UI widgets and styles.

Step 3. XML file For ListView

Now we will make a listview.

  • For this, we need to make one layout file which will represent the each row layout of the listview.

Prepare a new XML file named listview_item.xml and add the following lines

Again, only one textview with some properties like, textcolor, textsize, textstyle, background color etc.

All the rows of the listview will get the view like above file.

Step 5. List Adapter

Every listview require adapter class for data management.

Make a new JAVA class and set the name ListAdapter.java

Code structure for ListAdapter.java is as the following

Starring at adapter

Read the below lines

Compiler will first make context and integer array.

Then there is constructor which has two parameters.

We will initialize our objects for context and integer array using these parameters.

Now consider the following method

Using this method, compiler will first inflate the layout file listview_item.xml

Now every children of listview will get the user interface developed by the listview_item.xml file.

After this, compiler will set the value of the textview.

Compiler will use integer array to populate the values in the textview.

Step 6. Final Updates

At last, we need to write some code in activity_main.xml and MainActivity.java files.

Source code for activity_main.xml looks like the below

Читайте также:  Профессиональный калькулятор для андроид

Just one listview and nothing else in this file.

Code block for MainActivity.java is as the below

Noticing the above

Consider the below source code

First line is giving us the object of the Listview.

Second is defining one integer array. This integer holds the values from 1 to 18.

Third line is making an object of the ListAdapter class.

Now see the following coding lines

First, compiler will create an object of the LayoutInflater class.

Using this inflater, compiler has inflate the header_view.xml file in the second line.

Third line is important. We are setting up the header file in this line using addheaderView() method.

Attend the following code block

First line will inflate the footer_view to initialize the object (footerView) of the View class.

Then compiler will stick the footer to the listview using addFooterView() method.

Finally, above code will set the adapter into listview and our listview is ready with sticky header and footer.

2. Android ListView Sticky Header Like iphone | Pinned header listview

We will develop Android ListView Sticky Header Like iphone example in this tutorial.

Sometimes you want to make pinned header listview in android app.

This example will guide you to make sticky or pinned header for listview in android studio.

Pinned header means that a header which have certain number of child rows and this header sticks at the top of the ListView.

Then, again there will be another sticky header which will have certain number of children and it replaces old header.

You may have notice this type of listview in iphone or ios.

Android does not have any built in method or class to achieve this type of user interface for listview.

We need to customize out traditional listview and adapter class for this purpose.

Last Views For Header

Step 1. Adding Colors

I will separate the headers and children with different colors.

Also, different headers may have different colors.

So let us add some colors in res->values->colors.xml file.

Write the following lines in res->values->colors.xml file.

I have added blue, green, red and orange colors.

You can add many more colors as per your requirements.

Step 2. Adding Image

In this example we need to add one image in the drawable folder.

Download this image by clicking the below link

[sociallocker]Download scrollbarlight Image[/sociallocker]

After downloading the image, add it into res->drawable directory.

We need this image in HeaderListView class which we will create in the next step.

Step 3. Preparing HeaderListView And Section Adapter Class

Create a new JAVA class and give it a name HeaderListView.java

Copy the below code block in HeaderListView.java class

This class helps us to make a special listview which can support the sticky header.

Above class is the transformation from traditional listview to our desired listview.

Now make another new JAVA class named SectionAdapter.java

Write down the following Coding lines in SectionAdapter.java

For special listview, we also need to have special adapter with it.

Above class is making that special adapter for our special listview.

We will extend this adapter while creating the actual adapter for our listview.

Step 4. Ios Adapter

Let us create an adapter what will populate out listview with pinned header.

Make a new class and give it a name IosAdapter.java

Following is the code structure for IosAdapter.java class

Looking Deeply

Let us look what the above class IosAdapter will do actually.

Consider below code

  • This method will return the total number of sticky or pinned headers.

Look the following code

Above method is returning the total number of child for ant specific header.

Number of header is at the parameter (int section)

Above method will return 5 as the number of children for header at the position (int section)

getRowView()

code for above method

Above method will generate the view for the children items.

We will also set the text for children in this method.

Address of child can be like a child of the header at -> position section and a child position for that header is -> int row

Following method getSectionHeaderView() is making a layout for header

First parameter of getSectionHeaderView() method is the position (int section) for header.

We will set the name of the header in this method.

I have also set the background colors in this method using switch statement.

Handling Click Events

To handle the click events of the listview, review the below method

You can have both header and row position in this click event.

Step 5. Main Updates

Now last thing is to update activity_main.xml and MainActivity.java files.

Write the following coding lines in activity_main.xml

As you can see in the above code, I have used HeaderListView class to define listview.

It is referencing that HeaderListView which we have created in the step 3.

Here, in this line , you need to replace it with the package name of your android studio code.

You can find your package name in AndroidManifest.xml file.

Now make following source code in MainActivity.java

In this main class, we just need to set up the listview with proper adapter.

We will set the object of IosAdapter class to the listview.

3. Android Multi Column ListView With Sticky Header Example

Android Multi Column ListView With Sticky Header Example is today’s shining topic.

Multi column listview means that every row of the listview have more than one column and this listview is developing a table like structure.

You need to create a ListView with multiple columns in many applications to show multiple data.

Sometimes you want to have a static headers and just below that header, you want multi column listview.

For example, to show a order summary of any restaurant, you have two sticky headers like name of the restaurant and name of the customer.

Just after these two headers, your listview starts where every row includes columns like name of product, price of product, quantity of product etc.

We will develop just this kind of example in this article.

See Our MultiColumn ListView

Step 1. Making a List Item File

For creating a ListView, we need to make separate xml layout file.

This layout file represents the whole view structure of each listview row item.

So make a new file named list_item.xml in res->layout structure.

Add the below source code in list_item.xml file.

  • In listview, we have two columns in every row item. One column is showing product name and another is showing the quantity of the product.
  • In the above list_item.xml file, two textviews are representing these two columns.
  • We will use this list_item.xml file in the adapter class where compiler will inflate it in every iteration while making each row for listview.

Step 2. Food Model

The proper way to make a reliable listview in every scenario is to make a listview with help of the model class.

Model class includes getter and setter methods for data maintenance.

For example, in our example we have data in the form of product name and it’s quantity.

We can store product name in String and quantity in integer format.

Create a new java class named FoodModel.java in your app.

Following is the coding lines for FoodModel.java class

  • As I have said earlier, above model class includes get and set method for both product name and quantity.

Step 3. Food Adapter Class

Now let us create a food adapter class which will generate data set for the listview.

Prepare a new java class and set it’s name as FoodAdapter.java

Читайте также:  Отключить звук блокировки экрана андроид

Write down the following lines in FoodAdapter.java class

Diving Step by Step

Hang on, we will now understand above code one by one snippets.

Consider the below code snippet

  • First line is creating object of context.
  • Second is creating an ArrayList with the objects of the FoodModel class.
  • This arraylist (foodModelArrayList) is our main data provider. We are filling this arraylist (foodModelArrayList) with data in Main Activity. We will see this in next step.
  • Then I have created one Constructor. We will get context and arraylist (foodModelArrayList) via the parameters of this constructor.

Look at the below lines

  • Above are necessary method to be overriden. Mainly I have used that arraylist (foodModelArrayList) in above methods.

Read the following code snippet

Above getView() creates every row of the listview.

This method is called for the number of times which is equal to the number of rows of the listview.

For example, if listview have five rows then getView() method is called for five times.

In this getView() method, compiler will first inflate the row layout (list_item.xml) which we have already created in step 1.

Then we will fill the values of two textviews. (One is for product name and another is for quantity.)

We are using arraylist (foodModelArrayList) to fill the values in textviews.

Step 4. Making Final Changes

Now let us create our app’s main layout structure.

For this, you need to replace your existing code of activity_main.xml with the following one

In the above file, I have added three sticky or static headers. It means that these headers can not be changed or modified.

First two TextViews and LinearLayout with horizontal orientation represents these three sticky headers.

Just below these headers, I have added our multi column listview.

After this, write down the below code snippet in MainActivity.java file.

What does above code means ?

See the below snippet

First line is creating one string array called Products. It includes the names of the various food products.

Similarly, second line is creating one integer array which holds the quantity of the food products.

Third and fourth lines are making objects ArrayList and Listview respectively.

Attend below lines

Second line is creating a new object of FoodAdapter class and third one is setting this adapter object with the ListView.

First line will insert the data in foodModelArrayList using populateList() method.

populateList() method holds the below code

  • One for loop is there with six iterations.
  • In every iteration, compiler will create the object of the FoodModel class.

Then it will set the product name and quantity to this object. After this, the compiler adds this object in the arraylist.

4. Android ListView Section Header Example Group By Header

I will explain about android listview section header with example in this article.

You will make a listview with a specific header between it’s row items.

Last Views

After all of this hard work, you should get the listview like below video

What is Section Header ?

Section header means that a header among listview items to sort them with particular category.

For example, you are making listview with county names. Now countries can be categorized by continents.

So, you will make the first row as a section header which have continent name like Asia. Then in the second, third row you will write Asian countries like India, Chine etc.

After Asia, again you will make listview row as a section header and will name it Europe and further this process continues.

In this example, we will group listview by vehicle type as a header. We will create custom view for header which is different than the normal listview item.

So let us follow all the below steps carefully.

Step 1. Layout Resources

Different layout for header and normal rows requires different layout xml files. Hence, we will create two layout resources files.

Make two xml files res->layout directory.

Give a name lv_child.xml to first file and lv_header.xml to second xml file.

Add below code in lv_child.xml

Above file will create the layout for normal listview row items.

Copy following code in lv_header.xml

This code will generate the layout for header rows.

Step 2. Separate Classes

We need to create two java classes for both normal and header rows.

This class will work as a general model class. So make two new java classes and name them HeaderModel.java and ChildModel.java respectively.

Write down the below code in HeaderModel.java

isHeader() method will tell compiler whether the listview row is a header row or a normal row.

setheader(String header) method will set the string as a header title which passes as a parameter.

getName() method will return a header text in a string format.

Now add the below code in ChildModel.java

Similar methods are used here as HeaderModel.java class. Only difference is that get method will return normal row item text and set method will set the text as a row item name.

Step 3. Custom Adapter

As always, every listview requires an adapter class which will provide the data to populate the listview rows.

Make a new java class named CustomeAdapter.java and add below code in it.

Here I am populating listview with the help of the listItemArraylist.

listItemArraylist is created in the Main activity and passed as a parameter to the constructor of this adapter class.

Hence, let us first understand the Main Activity so it would be easier to understand adapter class.

Step 4. Final Codes

Now the final task is to write Main Activity code.

Add below code in activity_main.xml

Write the following code in MainActivity.java file

Diving Deep In Main Activity

Consider below code

First string array vehicleTypes will provide the header names.

Secong string array childnames will provide the text names for normal listview rows.

listItemArraylist is defined as below

Here ListItem is an Interface which in implemented by both model classes : HeaderModel.java and ChildModel.java.

So the methods present is the ListItem interface are overriden in HeaderModel.java and ChildModel.java.

Following is the code for the Interface ListItem

As we have seen earlier in Step 2 that both the methods of Interface ListItem are overriden in HeaderModel.java and ChildModel.java.

Now we will create data structure using populateList() method.

Below is the source code for the populateList() method.

Here I have make four child rows for each header.

Listview will start with the first header then four rows will be it’s child items. The fifth row will be second header and then four rows will be the child row for second header and it continues in this fashion.

So the first, sixth, eleventh and sixteenth row of the listview will be header rows.

Hence in the for loop if condition will be true for four times.

When the if condition is true, object of the HeaderModel will be added to the listIemArrayList

In all other for loop iterations, object of the ChildModel will be added to the listIemArrayList.

After completion of for loop, listIemArrayList is passed to the adapter constructor.

Now let’s see the adapter code.

Understanding Adapter

Read the below code for getView() method

This method will fetch the data from listIemArrayList and will populate the listview using that data.

Look at the following codes

It will check for the header object by using isHeader() method.

If isHeader() method returns true then compiler will inflate the lv_header.xml file as a listview row layout.

Otherwise it will inflate the lv_child.xml

After checking for above conditions and inflating the layout file compiler will set the text pf the listview row using the below line

Источник

Оцените статью