1°) Simple list view :
* Créer un layout avec un composant de type list view :
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
* Dans le code de l’activité :
Précisez : extends ListActivity {
Manipulation de la liste :
lv1=getListView();
//-- Affectation à la liste de type "simple_selectable_list_item" d'un tableau lv_arr via ArrayAdapter
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_selectable_list_item, lv_arr));
//-- Gestion du click sur une ligne de la liste
lv1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
//-- Gestion du click sur la ligne
Toast.makeText(MainActivity.this,"Vous avez sélectionné la ligne : "+(arg2+1)+" valeur : "+lv_arr.get(arg2)
,Toast.LENGTH_LONG).show();
finish();
}});
2°) List view avec saisie pour recherche :
package com.example.listviewbox;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private ListView lv1;
private EditText ed;
private ArrayList<String> lv_arr= new ArrayList<String>();
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
@Override
public void onCreate(Bundle icicle)
{super.onCreate(icicle);
setContentView(R.layout.activity_main);
//-- initialisation test du tableau
lv_arr.add("Playboy");
lv_arr.add("Simpsons");
lv_arr.add("Mario");
lv_arr.add("Indiana Jones");
lv_arr.add("Whirlwind");
lv_arr.add("Star Wars");
//-- Tri par ordre alphabétique du tableau
Collections.sort(lv_arr, comperator);
//-- Gestion de la list View
ed=(EditText)findViewById(R.id.EditText01);
lv1=getListView();
//-- Affectation à la liste de type "simple_selectable_list_item" d'un tableau lv_arr via ArrayAdapter
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, lv_arr));
//-- Gestion du click sur une ligne de la liste
lv1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(MainActivity.this,"Vous avez sélectionné la ligne : "+(arg2+1)+" valeur : "+lv_arr.get(arg2)
,Toast.LENGTH_LONG).show();
finish();
}});
//-- Observation de la saisie dans le champ texte
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count)
{textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<lv_arr.size();i++)
{if(textlength<=lv_arr.get(i).length())
{if(ed.getText().toString().equalsIgnoreCase((String) lv_arr.get(i).subSequence(0, textlength)))
arr_sort.add(lv_arr.get(i));
}
}
lv1.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1 , arr_sort));
}
});
}
//-- Pour le tri du tableau
Comparator<String> comperator = new Comparator<String>() {
public int compare(String object1, String object2) {
return object1.compareToIgnoreCase(object2);}};
}
2°) List view multiple avec case à cocher :
Créez un layout pour les lignes de la listview dans /res/layout/row.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="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher"/>
<CheckedTextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"/>
</LinearLayout>
Layout de l’activité :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/getresult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Result"/>
<ListView
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Activité :
package com.andrologiciels.andromultisel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView myListView;
Button getResult;
private ArrayList<String> dayOfWeekList = new ArrayList<String>();
private void initDayOfWeekList(){
dayOfWeekList.add("Sunday");
dayOfWeekList.add("Monday");
dayOfWeekList.add("Tuesday");
dayOfWeekList.add("Wednesday");
dayOfWeekList.add("Thursday");
dayOfWeekList.add("Friday");
dayOfWeekList.add("Saturday");
dayOfWeekList.add("Dimanche");
dayOfWeekList.add("Lundi");
dayOfWeekList.add("Mardi");
dayOfWeekList.add("Mercredi");
dayOfWeekList.add("Jeudi");
dayOfWeekList.add("Vendredi");
dayOfWeekList.add("Samedi");
}
MyArrayAdapter myArrayAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initDayOfWeekList();
setContentView(R.layout.activity_main);
myListView = (ListView)findViewById(R.id.list);
myArrayAdapter = new MyArrayAdapter(
this,
R.layout.row,
android.R.id.text1,
dayOfWeekList
);
myListView.setAdapter(myArrayAdapter);
myListView.setOnItemClickListener(myOnItemClickListener);
getResult = (Button)findViewById(R.id.getresult);
getResult.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
String result = "";
List<String> resultList = myArrayAdapter.getCheckedItems();
for(int i = 0; i < resultList.size(); i++){
result += String.valueOf(resultList.get(i)) + "\n";
}
myArrayAdapter.getCheckedItemPositions().toString();
Toast.makeText(
getApplicationContext(),
result,
Toast.LENGTH_LONG).show();
}});
}
OnItemClickListener myOnItemClickListener
= new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
myArrayAdapter.toggleChecked(position);
}};
private class MyArrayAdapter extends ArrayAdapter<String>{
private HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
public MyArrayAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
for(int i = 0; i < objects.size(); i++){
myChecked.put(i, false);
}
}
public void toggleChecked(int position){
if(myChecked.get(position)){
myChecked.put(position, false);
}else{
myChecked.put(position, true);
}
notifyDataSetChanged();
}
public List<Integer> getCheckedItemPositions(){
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItemPositions).add(i);
}
}
return checkedItemPositions;
}
public List<String> getCheckedItems(){
List<String> checkedItems = new ArrayList<String>();
for(int i = 0; i < myChecked.size(); i++){
if (myChecked.get(i)){
(checkedItems).add(dayOfWeekList.get(i));
}
}
return checkedItems;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.text1);
checkedTextView.setText(dayOfWeekList.get(position));
Boolean checked = myChecked.get(position);
if (checked != null) {
checkedTextView.setChecked(checked);
}
return row;
}
}
}
Le code est ici
3°) ListView sur deux lignes :
L’utilisation de la list view de deux lignes « android.R.layout.simple_list_item_2″ est basée sur 2 textview contenus dans le layout. Ces deux textview doivent être alimentés selon la méthode :
ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_2, android.R.id.text1, list) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text1.setText(persons.get(position).getName());
text2.setText(persons.get(position).getAge());
return view;
}
};
listView.setAdapter(adapter);
Dans cet exemple, il faut définir une classe « persons » :
class Person {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
La solution la plus élégante est de définir un tableau à deux dimensions (string [][] tab2D={{« Ligne1″, »Ligne2 »},{« Ligne2.1″, »Ligne2.2 »}} et d’utiliser un HasMap :
//HashMap links each line of data to the correct TextView
HashMap<String,String> item;
for(int i=0;i<StatesAndCapitals.length;i++){
item = new HashMap<String,String>();
item.put( "line1", tab2D[i][0]);
item.put( "line2", tab2D[i][1]);
list.add( item );
}
sa = new SimpleAdapter(this, list,
android.R.layout.simple_list_item_2,
new String[] { "line1","line2" },
new int[] {android.R.id.text1, android.R.id.text2});
setListAdapter(sa);
Pour customiser l’affichage il est possible de changer le layout « android.R.layout.simple_list_item_2 » par un layout personnalisé (et en changeant les champs android.R.id.text1 et android.R.id.text2). Exemple de layout customisé :
<?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="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/line_a"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:textStyle="italic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/line_b"
android:textSize="12sp"
android:textColor="#BFFF00"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Références :
http://tekeye.biz/2012/two-line-lists-in-android
4°) Gestion de la list view vide :
Insérez dans le code du Layout de la ListView :
<TextView android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:text="...........No data"
android:textColor="#FFFFFF"/>
L’id doit être « @android:id/empty » le type peut être n’importe lequel
6°) Gestion du click sur plusieurs boutons :
public class Mtest extends Activity {
Button b1;
Button b2;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler1);
b2.setOnClickListener(myhandler2);
...
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
}
};
}
Pour raffraichir une listview : lv1.invalidateViews();
Références :
Listview alimentée à partir d’une base de données
https://github.com/codepath/android_guides/wiki/Populating-a-ListView-with-a-CursorAdapter
Creating Customized List View Item Layout
http://www.androidinterview.com/android-custom-listview-with-image-and-text-using-arrayadapter/
http://www.learn2crack.com/2013/10/android-custom-listview-images-text-example.html
Votre commentaire