Android list with image

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, который содержит название элемента и его содержимое, если он чекнут.

Читайте также:  Hd videobox для андроид как работает

Создайте следующий Адаптер. Этот Адаптер добавит обработку изменения 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 ListFragment with Images and Text using Android Support Library

In this article, we will develop an Android application which lists a set of countries with their names, currencies and flags. For listing the countries, we are using the ListFragment class.

The screenshot of this application is shown in Figure 6.

This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) .

1. Create new Android application project namely “ListFragmentImagesText”

Figure 1 : Create new Android application project

2. Configure the application project

Figure 2 : Configure the application project

3. Design application launcher icon

Figure 3 : Design application launcher icon

4. Create a blank activity

Figure 4 : Create a blank activity

5. Enter MainActivity Details

Figure 5 : Enter MainActivity Details

6. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

7. Download and extract the zip file containing flag’s images to the directory /res/drawable

8. Update the layout file res/layout/activity_main.xml

9. Create a layout file listview_layout.xml in the folder res/layout

10. Create a ListFragment class in the file src/in/wptrafficanalyzer/listfragmentimagestext/CountryList.java

11. Update the file src/in/wptrafficanalyzer/listfragmentimagestext/MainActivity.java

12. Screenshot of the application

Figure 6 : Screenshot of the application in execution

13. Download source code

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

Ready to test your knowledge in Android? Take this quiz :

Источник

Using lists in Android wth ListView — Tutorial

This tutorial describes how to use ListView together with activities and fragments in Android.

1. Using lists in Android

The display of elements in a list is a very common pattern in mobile applications. The user sees a list of items and can scroll through them. Such an activity is depicted in the following picture.

Typically the user interacts with the list via the toolbar, for example, via a button which refreshes the list. Individual list items can be selected. This selection can update the toolbar or can trigger a detailed screen for the selection. The following graphic sketches that. On the selection of a list item another activity is started.

2. Android and the ListView widget

2.1. Views for handling lists

Android provides the ListView and the ExpandableListView classes which are capable of displaying a scrollable list of items. The ExpandableListView class supports a grouping of items.

2.2. Possible input types for lists

The input of a list (items in the list) can be arbitrary Java objects. The adapter extracts the correct data from the data object and assigns this data to the views in the row of the ListView .

These items are typically called the data model of the list. An adapter can receive data as input.

2.3. Adapters

An adapter manages the data model and adapts it to the individual entries in the widget. An adapter extends the BaseAdapter class.

Every line in the widget displaying the data consists of a layout which can be as complex as you want. A typical line in a list has an image on the left side and two text lines in the middle as depicted in the following graphic.

A layout file for such a line might look like the following.

Читайте также:  Платформа разработки для android

The adapter would inflate the layout for each row in its getView() method and assign the data to the individual views in the row.

The adapter is assigned to the ListView via the setAdapter method on the ListView object.

Adapters are not only used by ListView , but also by other views which extend AdapterView as, for example, Spinner , GridView , Gallery and StackView .

2.4. Filtering and sorting

The filtering and sorting of the data is handled by the adapter. You need to implement the logic in your custom adapter implementation.

2.5. Data updates in the adapter

The notifyDataSetChanged() method on the adapter is called if the data has changed or if new data is available.

The notifyDataSetInvalidated() method is called if the data is not available anymore.

2.6. Listener

To react to selections in the list, set an OnItemClickListener to your ListView .

3. Default adapter

3.1. Default platform adapter

Android provides default adapter implementations; the most important are ArrayAdapter and CursorAdapter . ArrayAdapter can handle data based on Arrays or java.util.List . SimpleCursorAdapter can handle database related data.

3.2. Using ArrayAdapter

The ArrayAdapter class can handle a list or arrays of Java objects as input. Every Java object is mapped to one row. By default, it maps the toString() method of the object to a view in the row layout.

You can define the ID of the view in the constructor of the ArrayAdapter otherwise the android.R.id.text1 ID is used as default.

The ArrayAdapter class allows to remove all elements in its underlying data structure with the clear() method call. You can then add new elements via the add() method or a Collection via the addAll() method.

You can also directly modify the underlying data structure and call the notifyDataSetChanged() method on the adapter to notify it about the changes in data.

If you want to change the data in your adapter, the underlying data structure must support this operation. This is, for example, the case for the ArrayList class, but not for arrays.

3.3. ListView example with ArrayAdapter

The following listing shows a layout file called activity_listviewexampleactivity.xml which includes a ListView .

The following example shows the usage of the ListView view in an activity. It uses a default layout from the Android platform for the row layout. It also demonstrates the removal of list items and uses animations for the removal.

4. Custom adapter implementations

4.1. Developing a custom adapter

The ArrayAdapter is limited as it supports only the mapping of toString() to one view in the row layout. To control the data assignment and to support several views, you have to create your custom adapter implementation.

For this you would extend an existing adapter implementation or subclass the BaseAdapter class directly.

Frequently you extend ArrayAdapter to write a custom adapter, as this is simpler than extending BaseAdapter directly.

4.2. Preparing a row for the list

The adapter needs to create a layout for each row of the list. The ListView instance calls the getView() method on the adapter for each data element. In this method the adapter creates the row layout and maps the data to the views in the layout.

This root of the layout is typically a ViewGroup (layout manager) and contains several other views, e.g., an ImageView and a TextView . The following graphic shows a list with different layouts for odd and even rows.

Within the getView() method you would inflate an XML based layout and then set the content of the individual views based on the Java object for this row. To inflate the XML layout file, you can use the LayoutInflator system service.

This layout inflator service can get accessed via the getLayoutInflator() method of the activity or via the context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) method call.

After the adapter inflated the layout, it searches for the relevant views in the layout and fills them with the data. The individual elements in the layout can be found via the findViewById() method call on the top level view.

4.3. Example for a custom adapter

The following code shows an implementation of a custom adapter. This adapter assumes that you have two png files (no.png and ok.png) in one of your directory]]res/drawable folders. The coding inflates an XML layout file, finds the relevant views in the layout and sets their content based on the input data.

4.4. Updating the data model from the adapter

The row can also contain views which interact with the underlying data model via the adapter. For example, you can have a Checkbox in your row layout and if the Checkbox is selected, the underlying data is changed.

5. ListActivity and ListFragment

5.1. Default container for using ListView

Android provides specialized fragment and activity classes to simplify list handling.

The classes are the ListActivity class, if you want to use lists in activities, and the ListFragment class, if you want to use lists in fragments.

You do not have to assign a layout to these elements. If you do not define a layout, the activity or fragment contains a single ListView by default. ListActivity and ListFragment also allow you to override a onListItemClick() method for handling selection of list items.

Читайте также:  Borderlands 2 андроид без геймпада

Both classes allow you to set the adapter to the default ListView via the setListAdapter() method.

The following example code shows a simple ListFragment implementation.

The next example code demonstrates the usage of a ListActivity .

5.2. ListActivity and custom layout

You can use a custom layout with ListActivity or ListFragment . In this case the fragment or activity searches in the provided layout for a ListView with the predefined android:id attribute set to @android:id/list . This usage is demonstrated by the following code snippet.

If you do not use this ID or do not include a ListView into your layout, the application crashes once you try to display the activity or the fragment.

5.3. Placeholder for an empty list

You can also use a view with the @android:id/empty ID in your layout. The corresponding activity and fragment shows this view automatically if the ListView is empty and hides it otherwise. For example, you could display an error message in such a view.

6. Exercise: Using ListView and ListActivity

The following exercise demonstrates how to use a ListView in an ListActivity . You use the predefined ArrayAdapter class and an existing Android layout for the rows.

Create a new Android project called de.vogella.android.listactivity with the activity called MyListActivity .

Change MyListActivity class based on the following code example. Note that the setContentView() method is not used.

7. Exercise: ListActivity with custom layout

In our example your will define your layout for the rows and use it in your adapter.

Create the rowlayout.xml layout file in the directory]]res/layout folder of the de.vogella.android.listactivity project.

Change your activity so that it uses the new layout.

8. Tutorial: Implementing your customer adapter

The following uses two images «no.png» and «ok.png». I placed them in the «res/drawable-mdpi» folder. You must create your own icons. In case you do not find any icons just copy «icon.png» and use a drawing program to change it a little bit and create a second one.

Create the class MySimpleArrayAdapter which will serve as our adapter.

To use this adapter, change the activity to the following.

If you run this example you should get a list with different icons for the certain elements.

9. ListViews and performance

9.1. Motivation

Performance is especially important on Android as users expect fast reaction times. Compared to desktop computers an Android device is relatively slow from the hardware perspective.

This part describes how to reduce these operations to implement your custom list adapter efficiently. The default Android adapters like ArrayAdapter are already performance optimized.

9.2. Time consuming operations

Every view which gets inflated from an XML layout file will result in a Java object. Inflating layouts and creating Java objects are expensive with regards to time and memory consumption.

In addition using the findViewById() method is relatively time consuming, even though it is not as bad as XML inflating.

9.3. Avoiding layout inflation and object creation

A ListView typically contains more data than the number of displayed rows. If the user scrolls the list, then the rows and their associated views will be scrolled out of the visible area. The Java objects which represent the rows can be reused for newly visible rows.

If Android determines that a row is not visible anymore, it allows the getView() of the adapter method to reuse the associated view via the convertView parameter.

The adapter can assign new data to the views contained in the view hierarchy of the convertView . This avoids inflating an XML file and creating new Java objects.

In case Android cannot reuse a row, the Android system passes null to the convertView parameter. Therefore the adapter implementation needs to check for this.

9.4. View holder pattern

A ViewHolder implementation allows to avoid the findViewById() method in an adapter.

A ViewHolder class is typically a static inner class in your adapter which holds references to the relevant views in your layout. This reference is assigned to the row view as a tag via the setTag() method.

If we receive a convertView object, we can get the instance of the ViewHolder via the getTag() method and assign the new attributes to the views via the ViewHolder reference.

While this sounds complex this is approximately 15 % faster than using the findViewById() method.

9.5. Example

The following code shows a performance optimized adapter implementation which reuses existing views and implements the holder pattern.

10. Storing the selection of a view

By default a ListView has no selection mode active. You can activate it via the setChoiceMode() method call. Pass ListView.CHOICE_MODE_MULTIPLE for multiple selections or ListView.CHOICE_MODE_SINGLE for single selections to this method.

To get the selected items of a ListView , use the getCheckedItemPosition() for a single selection method or listView.getCheckedItemPositions() for multiple selections. If you have stable ID, you could also use the getCheckedItemIds() method to get the selected IDs.

Android already provides a default layout for this: the android.R.layout.simple_list_item_multiple_choice layout which contains a configured CheckedTextView view.

The following activities demonstrate how to use these selection modes. If you use these modes, the ListView stores the selected values. It is not persisted in your data model.

Источник

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