Lecture
In this lesson:
- use SimpleAdapter to build a list
- add and delete entries in the list
How to display data in the list using the SimpleAdapter we know. Now we will try to change this data. Make a list with the ability to delete and add entries. We will add the button and delete using the context menu.
Create a project:
Project name : P0511_SimpleAdapterData
Build Target : Android 2.3.3
Application name : SimpleAdapterData
Package name : ru.startandroid.develop.p0511simpleadapterdata
Create Activity : MainActivity
Screen main.xml :
<? xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
android: layout_width = "fill_parent"
android: layout_height = "fill_parent"
android: orientation = "vertical">
<Button
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: onClick = "onButtonClick"
android: text = "Add post">
</ Button>
<ListView
android: id = "@ + id / lvSimple"
android: layout_width = "match_parent"
android: layout_height = "wrap_content">
</ Listview>
</ LinearLayout>
Button to add and list. From interesting things you can note the onClick property of the button. Then it becomes clear what it is.
Layout for item list item.xml :
<? xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
xmlns: android = "http://schemas.android.com/apk/res/android"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: orientation = "horizontal">
<ImageView
android: id = "@ + id / ivImg"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: src = "@ drawable / ic_launcher">
</ ImageView>
<Textview
android: id = "@ + id / tvText"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_gravity = "center_vertical"
android: layout_marginLeft = "10dp"
android: text = ""
android: textSize = "18sp">
</ TextView>
</ LinearLayout>
Picture and text.
MainActivity.java code:
package ru.startandroid.develop.p0511simpleadapterdata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
private static final int CM_DELETE_ID = 1;
// имена атрибутов для Map
final String ATTRIBUTE_NAME_TEXT = "text";
final String ATTRIBUTE_NAME_IMAGE = "image";
ListView lvSimple;
SimpleAdapter sAdapter;
ArrayList<Map<String, Object>> data;
Map<String, Object> m;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// упаковываем данные в понятную для адаптера структуру
data = new ArrayList<Map<String, Object>>();
for (int i = 1; i < 5; i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_NAME_TEXT, "sometext " + i);
m.put(ATTRIBUTE_NAME_IMAGE, R.drawable.ic_launcher);
data.add(m);
}
// массив имен атрибутов, из которых будут читаться данные
String[] from = { ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_IMAGE };
// массив ID View-компонентов, в которые будут вставлять данные
int[] to = { R.id.tvText, R.id.ivImg };
// создаем адаптер
sAdapter = new SimpleAdapter(this, data, R.layout.item, from, to);
// определяем список и присваиваем ему адаптер
lvSimple = (ListView) findViewById(R.id.lvSimple);
lvSimple.setAdapter(sAdapter);
registerForContextMenu(lvSimple);
}
public void onButtonClick(View v) {
// создаем новый Map
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_NAME_TEXT, "sometext " + (data.size() + 1));
m.put(ATTRIBUTE_NAME_IMAGE, R.drawable.ic_launcher);
// добавляем его в коллекцию
data.add(m);
// уведомляем, что данные изменились
sAdapter.notifyDataSetChanged();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CM_DELETE_ID, 0, "Удалить запись");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId() == CM_DELETE_ID) {
// получаем инфу о пункте списка
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) item.getMenuInfo();
// удаляем Map из коллекции, используя позицию пункта в списке
data.remove(acmi.position);
// уведомляем, что данные изменились
sAdapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
}
In the onCreate method , we create a collection of Map objects, matching arrays, create an adapter and a list, add the option of the context menu for the list.
The onButtonClick method - we specified it in main.xml in the onClick property of the button. And now when you click on the button, this method will be executed. A separate click handler is not needed.
In this method, we create a new Map, add it to the data collection and inform that the data has changed and we need to update the list.
The onCreateContextMenu method creates a context menu. We create only one item - to delete the record.
In onContextItemSelected, we process the click on the context menu item. When you call the context menu, the object for which it was called, transfers information about itself to the menu. To get data on a list item for which the context menu call was made, we use the getMenuInfo method. The AdapterContextMenuInfo object contains data about the View, id and position of the list item. We use the position to remove the corresponding Map from the collection. After that we inform that the data has changed.
All save and run.
The screenshot shows the context menu, which is invoked with a long press on the list item. Behind it is a list and a button to add entries.
Entries are added and deleted. Editing I did not do. There is the same principle. Get the Map and change its attributes.
From the code it is clear that to update the list, you need to change the data used by the adapter and call its notification method.
In the next lesson:
- use SimpleCursorAdapter to build a list
- add and delete entries in the list
Comments
To leave a comment
Mobile Programming (Android IOs)
Terms: Mobile Programming (Android IOs)