Android listview with checkboxes

Содержание
  1. ListView в Android: Кастомизация списков
  2. Пример: ListActivity с собственным шаблоном.
  3. Пример: ListActivity с гибким шаблоном
  4. Продвинутые ListActivity
  5. Мультивыбор
  6. Хедер и Футер
  7. SimpleCursorAdapter
  8. Android ListView With CheckBoxes
  9. 3 Answers 3
  10. Linked
  11. Related
  12. Hot Network Questions
  13. Subscribe to RSS
  14. Android: ListView with Checkbox
  15. Android ListView Tutorial | CheckBox, Button, EditText, Image,Text
  16. 1. Android ListView With Image and Text
  17. Step 1. Create a new project
  18. Step 2. Necessary Images
  19. download this images
  20. Step 3. Update activity_main.xml
  21. Step 4. Create java class named CustomeAdapter.java
  22. Layout File
  23. Step 5. Create a class named ImageModel.java
  24. Step 6. Finally, update MainActivity.java class.
  25. 2. ListView with CheckBox In Android
  26. Step 1. Create a new project in the Android Studio.
  27. Step 2. Create a class named Model.java
  28. Step 3. Creating lv_item.xml layout file
  29. Step 4. Updating activity_main.xml
  30. Step 5. Create one class and name it: CustomAdapter.java
  31. Step 6. Copy and paste following code in MainActivity.java
  32. Step 7. Create a new activity and name it NextActivity.
  33. 3. Android ListView with EditText Example
  34. 1. Create a model class
  35. 2. Making ListView Item
  36. 3. Preparing Custom Adapter
  37. Explanation
  38. 4. Changing MainActivity
  39. Update your activity_main.xml
  40. 5. NextActivity Creation
  41. 4. Android ListView with Button Tutorial
  42. Step 1: Create a new project in the android studio.
  43. Step 2: Updating activity_main.xml file
  44. Step 3: Creating Model.java class
  45. Step 4: Creating Integer Resource File
  46. Step 5: Creating row layout for listview
  47. Step 6: Creating CustomAdapter.java class:
  48. Step 7: Setting tag for position and convertView
  49. Step 8: Getting tags in buttons onClick() method
  50. Step 9: Creating NextActivity
  51. Step 10: Updating NextActivtiy code
  52. Step 11: Updating MainActivity.java class
  53. 3 thoughts on “Android ListView Tutorial | CheckBox, Button, EditText, Image,Text”

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 With CheckBoxes

I’ve found a sample about populating a listView from a database in android,it works well,but I want to add some functionality to this application,I want to put a checkbox next to each item in my listview and when the user checks each item he will be able to delete that item by pressing a Confirm button.I’ve put these lines to make the multiple choice enabled,but the checkbox does not appear and I don’t know how to delete the selected Item !

Would you please help me solve my issue?

Here is my Code:

3 Answers 3

Create CustomAdapter for ListView ; create layout_row , which represents row in your ListView , and has structure — [text] [radio_button]

list_row Layout contains 2 Views — TextView (id = text), RadioButton (id = radioButtonChooser)

Look at Android Api Demos. Maybe best way is use example from List11.java. If your row item implements Checkable, the ListView will handle and keep checked position by itself. And don’t need handle it in your Adapter .

You should use your custom adapter, and you can reach all inflated layout’s controls its getView method.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Android: ListView with Checkbox

I’ve searched high and low for this issue but am not able to find something concrete.

Basically, I have a list of friends in a ListView and I am trying to create a group by choosing specific friends. To do this I have created an Activity with a SearchView and a ListView. Searching will filter and display friends that I want to add. To do so, I want to use a checkbox. All the «checked» friends will then be passed to another activity where the group creation can be complete.

The activity’s layout has a ListView . I have written my own adapter and this adapter inflates the row layout for the ListView. The layout of the adapter has a CheckBox that I have explicitly added.

So activity layout has: ListView Row layout has: TextView and Checkbox

But am having issues with: 1. Trying to keep the checkbox checked when scrolling/searching the listview as the view refreshes and the checkbox is recreated as unchecked — I’ve solved this for the time being by maintaining a list of the checkboxes clicked. I am doing this in the getView() method of the adapter. 2. Trying to determine which row of the ListView the checkbox belongs to. I’d need this to then create my group of friends. 3. Allowing to edit the list of chosen friends — to add/remove friends before creating the group.

Here is a diagrammatic representation:

EDIT

Adding in another diagram to show how it works.

So from the first activity, I go to the second one to search and add friends. Once I’ve chosen my friends, I send the list back to my first activity when I click on ‘OK’ button.

Источник

Android ListView Tutorial | CheckBox, Button, EditText, Image,Text

Android Listview with image and text example tutorial will guide you today.

This article consists four different example as the below table.

Listview is used when you want to display multiple items which have a dynamic number of items.

1. Android ListView With Image and Text

We will create a listview which contains image and text in it’s every row item.

I have put one divider between every listview row item. Divider helps user to differentiate among listview items easily.

Watch this video to have a brief idea about the output of this tutorial.

Step 1. Create a new project

Make a new project in the Android Studio.

Step 2. Necessary Images

We require few images in this example to use them in the listview.

Click on the below link to download these images.

download this images

Now put these images in the drawable folder.

Step 3. Update activity_main.xml

copy and paste following code

I have taken one listview in the above code.

Step 4. Create java class named CustomeAdapter.java

copy following code in it.

getView() method will create layout for every listview row item.

Below two lines from getView() method will set the Image and Text.

Compiler will get the appropriate object from the imageModelArrayList using position.

From that object, it will use getName() and getImage_drawable() method to get related text and image resource.

Layout File

While developing listview, we need to create adapter class in which we can define code for each cell of listview.

We need to create one layout resource file(lv_item.xml here in our example, you can name it as you like) in the resource folder.

This file will contain components like TextView,ImageView, etc. as per requirement.

This file represents a single cell of the listview. In our example it contains one ImageView and one TextView.

Thus, every row will contain one image and one text.

In getView() method, lv_item.xml is inflated, and all the components of lv_item can be set here for each cell of listview as per requirement.

Code for lv_item.xml is like:

Step 5. Create a class named ImageModel.java

Add following source code in it.

Step 6. Finally, update MainActivity.java class.

Copy and paste below code in MainActivity.java

Consider below source code

I have declared one integer array in above code.

This integer array includes the drawable references to the images which are stored in the drawable folder.

We have used this integer reference to set the images in the imageview in adapter class.

Above code have declared a string variable. This variable includes the names of the vehicles.

Adapter have used this string array to fill the text in every row of the listview.

Read below code for populateList() method

populateList() method will create one arraylist. This arraylist contains the objects of the ImageModel class.

Compiler will create the object of the ImageModel class and will add it into the arraylist in the every iteration of the for loop.

After the successful operation of populateList() method, we will send arraylist to the adapter.

Now run your project, and yes, it will work like shown in the video.

Читайте также:  При установке android studio нет установки sdk

If you have any questions regarding this tutorial, feel free to ask in comment section.

2. ListView with CheckBox In Android

In Listview with Checkbox in Android Studio example,learn how to make custom Listview with a checkbox.

You will have to create a listview with checkbox in Android Studio when you want to show certain options to the user and wants to take more than one options to be selected.

There is a common problem like “checkbox unchecked when I scroll listview.”

We will solve this problem in this listview with checkbox in Android Studio.

We will use listview’s onitemclicklistener() and checkbox’s OnClickListener() method to get checked items.

In this example, we will get single selection, multiple selection and also select all scenario.

Check out the output of Listview with Checkbox in Android Studio tutorial below which is prepared by Demonuts.com:

Step 1. Create a new project in the Android Studio.

Choose empty as your Main Activity.

Step 2. Create a class named Model.java

copy the following source code in it:

This class represents the various methods to set and get the data in the adapter class.

Objects of this class will be used to maintain the proper data structure.

Step 3. Creating lv_item.xml layout file

Create a new layout resource file named lv_item.xml file and add following

This file will create the layout for all the rows of the listview. Adapter class will use this file.

It contains one checkbox and one textview.

Step 4. Updating activity_main.xml

Copy and Paste following source code in activity_main.xml

I have taken one listview and three buttons in main layout.

Step 5. Create one class and name it: CustomAdapter.java

Copy and paste following code in this class:

We are getting one arraylist of the objects of the Model class in the constructor.

We are using this arraylist in the below method.

Now check following code snippet:

Check first two lines of above snippet. Two tags are set to checkbox

One for getting position (checkbox.setTag())

And other for getting whole row view in which checkbox is present. (checkbox.getTag())

To set the Tag of view, we need to assign key which is R.integer.btnplusview here.

When we are getting this view using getTag, we used the same key to get the whole view as shown in the checkbox.OnClickListener().

Now you might say what is R.integer.btnplusview??

It is nothing but same as you define your string resources in the string.xml, you can define your integer resources in an integer.xml file.

When you create a project in the android studio, string.xml is generated automatically, while you have to manually create integer.xml , that’s it, nothing special.

Create integer.xml under res/values directory(same directory in which string.xml is present) and copy following code:

The Logic for updating value of each model item is written on OnClickListener() of the checkbox.

We have used setTag and getTag to get which checkbox is clicked(position of clicked checkbox), and we can also get the whole view of row item which is clicked, and it is taken as tempview in above code.

Using tempview, you can inflate all views(TextView, EditText,ImageView etc.) of that particular row(row which is clicked).

TextView is inflated from tempview, and then we can get the value of this textview to use as per requirements.

Step 6. Copy and paste following code in MainActivity.java

There are three buttons in the above code snippet.

Below is the onclick for first one

When the user clicks on this button, all the checkboxes in the listview are automatically selected or checked.

Next button will take the user to the Next Activity.

Consider below code

When the user clicks the deselect button, all the checkboxes in the listview are deselected.

This select all and deselect all feature is very useful for user when he wants to do all the process from scratch.

Look at the below method

getModel() method will create an arraylist of the objects of the model class.

This arraylist is sent to the adapter class via constructor where it will work as the data provider.

Step 7. Create a new activity and name it NextActivity.

Now when clicking on Next button, a new activity opens with names of selected animals as shown in the output video.

So you will have two files: 1. NextActivity.java and 2. activity_next.xml

Copy and paste following code into NextActivity.java class:

for loop in the above code will check all the object one by one. It will print the animal name which are checked.

Copy following in activity_next.xml

Observe all the code snippets for listview with checkbox example carefully and understand it throughout so that you can change all things as per your different requirements.

All for Listview with Checkbox in Android Studio.

3. Android ListView with EditText Example

Android Listview Edittext With TextView Tutorial Example is today’s topic.

We will implement Custom Listview with EditText and will set and get text values of all edittext in all child elements of listview.

Many developers have oftern several problems regarding this topic like:

  1. Value of edittext changes when scrolling
  2. How to set edittext value in listview items
  3. How to retain edittext value while scrolling
  4. How to get all the text values of all the edittexts of listview and pass it to next activity.

Today’s tutorial will give perfect answers and solutions of above problems.

TextWatcher class is used to put logic when user enter text in any Edittext of Listview.

We will pass all the edittext values to next activity so that they can be used as per requirement of app.

Check out the output of Android Listview Edittext With TextView tutorial.

1. Create a model class

Create a new class named “EditModel.java” and copy below code

We will use objects of this model to perfectly retain the edittext value when scrolling listview.

Getter and Setter methods are the key for every mode class. So we have created in this model also.

2. Making ListView Item

Open new resource layout file and give it a name lv_item.xml

This is the complete view of every single row item of listview.

It contains a textview along with edittext.

3. Preparing Custom Adapter

Make a new java class named “CustomeAdapter.java”.

Add following into this class

Explanation

This class is the heart of the whole tutorial.

The main logic is inside this lines of code

When user enter any text value, above method will be called.

Now we are using an ArrayList of the objects of EditModel class. So every single object of EditModel class contains value of edittext.

Читайте также:  Androidmanifest xml android version

Now suppose, when user enters the text in the 1st edittext of listview, 1st object from ArrayList is called and the value of edittext is updated in that. Thus when user scrolls the listview, again listview will be populated and updated value of 1st edittext will be printed.

The ArrayList is defined as public static, so that it can be used in any other activity.

4. Changing MainActivity

Change you MainActivity.java class as per below

ListView is populated in MainActivity with the object of customAdapter class.

Button click event is also defined in above class.

Update your activity_main.xml

5. NextActivity Creation

Make a new activity and give it a name “NextActivity”

Now write following source code into NextActivity.java class

This class simply prints the text valued of all the edittexts.

We have used ArrayList of the objects of EdiModel class which was defined in CustomAdapter.

Add below into activity_next.xml

Thus, you have seen that implementing a custom listview with edittext and textview is not a big deal.

It is also easy to retain the value even when user scrolls the listview.

And finally, getting values of edittexts to any other future activities is also not complex.

4. Android ListView with Button Tutorial

Hello, In this listview with button android tutorial, you will learn how to use a button in listview item.

We will see how to handle button’s click listeners in every row item of listview.

I have created listview elements with multiple clickable buttons in this tutorial example.

There are some problems like

You click on first button, but system clicks on last button

Quantity number of item change when scroll the listview.

Implementing button in the listview is a little complex task.

But you can do it smoothly if you follow proper method with the efficient code snippets.

Getting the proper position of clicked button and set onclick event for button required some additional coding lines.

I will go through all these problems and teach you how to solve them easily.

First of all check out the output of this example, so that you can have an idea what we are developing at the end of the tutorial.

Step 1: Create a new project in the android studio.

Empty Activity is the option, you need to select when creating a new project in the android studio.

Step 2: Updating activity_main.xml file

Add following code into activity_main.xml file

Step 3: Creating Model.java class

Create a new class named Model.java and add following

This class represents the various methods to set and get the data in the adapter class.

Objects of this class will be used to maintain the proper data structure.

Step 4: Creating Integer Resource File

In this tutorial, we need to create integer resources.

Integer resources are same as string resources which are written at string.xml file in values directory.

To define integer resources, we need to create integer.xml file in values directory.

To create integer.xml file, right click on values folder -> New -> Value resource file

Copy following code in an integer.xml file

Step 5: Creating row layout for listview

Create one layout resource file and name it as lv_item.xml and copy below code

This layout file says us how every row of the listview will be look a like.

Mainly two textviews and two buttons are present in this file. One button will increase the fruit quantity and the other one decrease it.

One textview represnts the name of the fruit.

Other textview shows the quantity of that fruit in terms of numbers.

Step 6: Creating CustomAdapter.java class:

Create new java class named CustomAdapter and add following code

We are using an arraylist which is defined in the Main Activity.

This arraylist gives the data information to populate the listview.

Every object of the arraylist have value for fruit name and the quantity number.

Quantity number is changing with respect to the click event of plus and minus buttons.

Step 7: Setting tag for position and convertView

Look at this code

When listview is populating, we can set tags for postion and views as per above code.

We have set tags on btn_plus for position and converView.

setTag(key,value) method is used for this.

key for tag is used from the integer.xml file, we created earlier.

Your key should be unique for setting each tag.

Step 8: Getting tags in buttons onClick() method

You can get position and converView by using getTag(key) method.

We are setting tempview with view got from getTag() method.

In getTag() method we are using same key, which we used in setTag() method.

Similarly we can get position also using getTag() method and proper key.

Here tempview is a whole row view which contains two textView and two button.

You can inflate views of row view and set values to them. Here we are setting textView’s value by following code

Similarly, for btn_minus, all tags are set and get and values of textView are updated.

Step 9: Creating NextActivity

To open new activity in android studio, click on File tab which is present at the left top bar.

Now go to File->New->Activity->Empty Activity and give name of activity as NextActivity.

Step 10: Updating NextActivtiy code

Add following code into activity_next.xml

Add following into NextActivity.java class

Step 11: Updating MainActivity.java class

Put below code in MainActivity.java

Consider the below code

getModel() method creates an arraylist with the objects of the Model class.

This arraylist works as a data provider for the listview adapter.

Number of objects in the arraylist is equals to the number of rows in the listview.

So it was all about implementing listview with button android feature in our android app programmatically. Thank you and keep coding!

So we have considered all the possible examples of android listview widget.

3 thoughts on “Android ListView Tutorial | CheckBox, Button, EditText, Image,Text”

In edit text section, its like we know the number of edit text we want in our listview prior to creation, but what if we want to add edit text to listview on click during run time, like instead using for loop . Help me with this. Thanks

In my 40+ years of experience, I have read or watched hundreds of tutorials. Believe me when I say; this is one of the better ones.. Thanks.

in the Android ListView with EditText Example , I have entered all the code which compiles cleanly and the program runs, but when I select the textbox to type into, the keyboard appears and then does not allow me to type any text into the box. Any ideas why this should happen please?

Источник

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