Je veux créer un custom adapter
pour ma vue liste. Existe-t-il un article qui puisse me montrer comment en créer un et également expliquer son fonctionnement?
public class ListAdapter extends ArrayAdapter<Item> {
private int resourceLayout;
private Context mContext;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
Item p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.id);
TextView tt2 = (TextView) v.findViewById(R.id.categoryId);
TextView tt3 = (TextView) v.findViewById(R.id.description);
if (tt1 != null) {
tt1.setText(p.getId());
}
if (tt2 != null) {
tt2.setText(p.getCategory().getId());
}
if (tt3 != null) {
tt3.setText(p.getDescription());
}
}
return v;
}
}
C'est un cours que j'avais utilisé pour mon projet. Vous devez avoir une collection de vos éléments que vous souhaitez afficher. Dans mon cas, il s'agit de <Item>
Vous devez remplacer la méthode View getView(int position, View convertView, ViewGroup parent)
.
R.layout.itemlistrow
définit la ligne de la ListView
.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_height="wrap_content" Android:orientation="vertical"
Android:layout_width="fill_parent">
<TableRow Android:layout_width="fill_parent"
Android:id="@+id/TableRow01"
Android:layout_height="wrap_content">
<TextView Android:textColor="#FFFFFF"
Android:id="@+id/id"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"
Android:text="id" Android:textStyle="bold"
Android:gravity="left"
Android:layout_weight="1"
Android:typeface="monospace"
Android:height="40sp" />
</TableRow>
<TableRow Android:layout_height="wrap_content"
Android:layout_width="fill_parent">
<TextView Android:textColor="#FFFFFF"
Android:id="@+id/categoryId"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"
Android:text="categoryId"
Android:layout_weight="1"
Android:height="20sp" />
<TextView Android:layout_height="wrap_content"
Android:layout_width="fill_parent"
Android:layout_weight="1"
Android:textColor="#FFFFFF"
Android:gravity="right"
Android:id="@+id/description"
Android:text="description"
Android:height="20sp" />
</TableRow>
</TableLayout>
Dans MainActivity
, définissez ListView
comme ceci,
ListView yourListView = (ListView) findViewById(R.id.itemListView);
// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List<yourItem>);
yourListView .setAdapter(customAdapter);
Je sais que cela a déjà été répondu ... mais je voulais donner un exemple plus complet.
Dans mon exemple, la ListActivity
qui affichera notre ListView
personnalisée s'appelle OptionsActivity
, car dans mon projet, cette Activity
affichera les différentes options que mon utilisateur peut définir pour contrôler mon application. Il existe deux types d'élément de liste, un type d'élément de liste a simplement une TextView
et le second type d'élément de liste a juste une Button
. Vous pouvez mettre tous les widgets que vous aimez dans chaque type d'élément de liste, mais j'ai gardé cet exemple simple.
La méthode getItemView()
vérifie quels éléments de la liste doivent être de type 1 ou 2. En fonction de mes valeurs statiques définies précédemment, les 5 premiers éléments de la liste seront du type d'élément de liste 1 et les 5 derniers éléments de la liste seront du type d'élément de liste. 2. Donc, si vous compilez et exécutez ceci, vous aurez une ListView
qui ne contient que cinq éléments contenant uniquement un Button
, puis cinq éléments contenant uniquement un TextView
.
Vous trouverez ci-dessous le code Activity
, le fichier XML d'activité et un fichier XML pour chaque type d'élément de liste.
OptionsActivity.Java:
public class OptionsActivity extends ListActivity {
private static final int LIST_ITEM_TYPE_1 = 0;
private static final int LIST_ITEM_TYPE_2 = 1;
private static final int LIST_ITEM_TYPE_COUNT = 2;
private static final int LIST_ITEM_COUNT = 10;
// The first five list items will be list item type 1
// and the last five will be list item type 2
private static final int LIST_ITEM_TYPE_1_COUNT = 5;
private MyCustomAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
for (int i = 0; i < LIST_ITEM_COUNT; i++) {
if (i < LIST_ITEM_TYPE_1_COUNT)
mAdapter.addItem("item type 1");
else
mAdapter.addItem("item type 2");
}
setListAdapter(mAdapter);
}
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if(position < LIST_ITEM_TYPE_1_COUNT)
return LIST_ITEM_TYPE_1;
else
return LIST_ITEM_TYPE_2;
}
@Override
public int getViewTypeCount() {
return LIST_ITEM_TYPE_COUNT;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public String getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch(type) {
case LIST_ITEM_TYPE_1:
convertView = mInflater.inflate(R.layout.list_item_type1, null);
holder.textView = (TextView)convertView.findViewById(R.id.list_item_type1_text_view);
break;
case LIST_ITEM_TYPE_2:
convertView = mInflater.inflate(R.layout.list_item_type2, null);
holder.textView = (TextView)convertView.findViewById(R.id.list_item_type2_button);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
activity_options.xml:
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:id="@+id/container"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical"
>
<ListView
Android:id="@+id/optionsList"
Android:layout_width="match_parent"
Android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list_item_type_1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:id="@+id/list_item_type1_layout"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical" >
<TextView
Android:id="@+id/list_item_type1_text_view"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Text goes here" />
</LinearLayout>
list_item_type2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:id="@+id/list_item_type2_layout"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical" >
<Button
Android:id="@+id/list_item_type2_button"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Button text goes here" />
</LinearLayout>
Ce code est facile à comprendre.
three_horizontal_text_views_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:orientation="horizontal" Android:layout_width="match_parent"
Android:layout_height="match_parent">
<TextView
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:id="@+id/leftTextView"/>
<TextView
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:id="@+id/centreTextView"/>
<TextView
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:id="@+id/rightTextView"/>
</LinearLayout>
ThreeStrings.Java
public class ThreeStrings {
private String left;
private String right;
private String centre;
public ThreeStrings(String left, String right, String centre) {
this.left = left;
this.right = right;
this.centre = centre;
}
}
ThreeHorizontalTextViewsAdapter.Java
public class ThreeHorizontalTextViewsAdapter extends ArrayAdapter<ThreeStrings> {
private int layoutResource;
public ThreeHorizontalTextViewsAdapter(Context context, int layoutResource, List<ThreeStrings> threeStringsList) {
super(context, layoutResource, threeStringsList);
this.layoutResource = layoutResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(layoutResource, null);
}
ThreeStrings threeStrings = getItem(position);
if (threeStrings != null) {
TextView leftTextView = (TextView) view.findViewById(R.id.leftTextView);
TextView rightTextView = (TextView) view.findViewById(R.id.rightTextView);
TextView centreTextView = (TextView) view.findViewById(R.id.centreTextView);
if (leftTextView != null) {
leftTextView.setText(threeStrings.getLeft());
}
if (rightTextView != null) {
rightTextView.setText(threeStrings.getRight());
}
if (centreTextView != null) {
centreTextView.setText(threeStrings.getCentre());
}
}
return view;
}
}
main_layout.xml
<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:paddingLeft="@dimen/activity_horizontal_margin"
Android:paddingRight="@dimen/activity_horizontal_margin"
Android:paddingTop="@dimen/activity_vertical_margin"
Android:paddingBottom="@dimen/activity_vertical_margin"
Android:orientation="vertical"
tools:context="com.androidapplication.ListActivity">
<ListView
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:id="@+id/listView"></ListView>
</LinearLayout>
MainActivity.Java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<ThreeStrings> threeStringsList = new ArrayList<>();
ThreeStrings threeStrings = new ThreeStrings("a", "b", "c");
threeStringsList.add(threeStrings);
ListView listView = (ListView)findViewById(R.id.listView);
ThreeHorizontalTextViewsAdapter threeHorizontalTextViewsAdapter = new ThreeHorizontalTextViewsAdapter(this, R.layout.three_horizontal_text_views_layout, threeStringsList);
listView.setAdapter(threeHorizontalTextViewsAdapter);
}
//......}
Google a un exemple appelé EfficientAdapter, qui, à mon avis, est le meilleur exemple simple de mise en œuvre d'adaptateurs personnalisés. http://developer.Android.com/resources/samples/ApiDemos/src/com/example/Android/apis/view/List14.html @ CommonsWare a écrit une bonne explication des modèles utilisés dans l'exemple ci-dessus http://commonsware.com/Android/excerpt.pdf
Vous pouvez consulter cet exemple dans ApiDemos officiel. Il montre comment étendre BaseAdapter
et l'appliquer à ListView
. Après cela, il suffit de regarder la référence pour BaseAdapter
et d’essayer de comprendre ce que fait chaque méthode (y compris celles héritées) et quand/comment l’utiliser.
En outre, Google est votre ami :).
Vérifiez ce lien , très simplement via la convertView
, nous pouvons obtenir la disposition d’une ligne qui sera affichée dans listview (qui est la parentView
).
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
}
en utilisant la position, vous pouvez obtenir les objets du List<Item>
.
Item p = items.get(position);
après cela, nous devrons définir les détails souhaités de l'objet sur les widgets de formulaire identifiés.
if (p != null) {
TextView tt = (TextView) v.findViewById(R.id.id);
TextView tt1 = (TextView) v.findViewById(R.id.categoryId);
TextView tt3 = (TextView) v.findViewById(R.id.description);
if (tt != null) {
tt.setText(p.getId());
}
if (tt1 != null) {
tt1.setText(p.getCategory().getId());
}
if (tt3 != null) {
tt3.setText(p.getDescription());
}
}
alors il retournera la vue construite qui sera attachée à la parentView
(qui est une ListView
/GridView
).
Voici la marche à suivre complète pour créer un adaptateur personnalisé pour l'affichage sous forme de liste, étape par étape -
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
public class DataModel {
String name;
String type;
String version_number;
String feature;
public DataModel(String name, String type, String version_number, String feature ) {
this.name=name;
this.type=type;
this.version_number=version_number;
this.feature=feature;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getVersion_number() {
return version_number;
}
public String getFeature() {
return feature;
}
}
public class CustomAdapter extends ArrayAdapter<DataModel> implements View.OnClickListener{
private ArrayList<DataModel> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtVersion;
ImageView info;
}
public CustomAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.row_item, data);
this.dataSet = data;
this.mContext=context;
}
@Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
DataModel dataModel=(DataModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "Release date " +dataModel.getFeature(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
DataModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item, parent, null);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);
viewHolder.txtType = (TextView) convertView.findViewById(R.id.type);
viewHolder.txtVersion = (TextView) convertView.findViewById(R.id.version_number);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(dataModel.getName());
viewHolder.txtType.setText(dataModel.getType());
viewHolder.txtVersion.setText(dataModel.getVersion_number());
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
// Return the completed view to render on screen
return convertView;
}
}
public class MainActivity extends AppCompatActivity {
ArrayList<DataModel> dataModels;
ListView listView;
private static CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView=(ListView)findViewById(R.id.list);
dataModels= new ArrayList<>();
dataModels.add(new DataModel("Apple Pie", "Android 1.0", "1","September 23, 2008"));
dataModels.add(new DataModel("Banana Bread", "Android 1.1", "2","February 9, 2009"));
dataModels.add(new DataModel("Cupcake", "Android 1.5", "3","April 27, 2009"));
dataModels.add(new DataModel("Donut","Android 1.6","4","September 15, 2009"));
dataModels.add(new DataModel("Eclair", "Android 2.0", "5","October 26, 2009"));
dataModels.add(new DataModel("Froyo", "Android 2.2", "8","May 20, 2010"));
dataModels.add(new DataModel("Gingerbread", "Android 2.3", "9","December 6, 2010"));
dataModels.add(new DataModel("Honeycomb","Android 3.0","11","February 22, 2011"));
dataModels.add(new DataModel("Ice cream sandwich", "Android 4.0", "14","October 18, 2011"));
dataModels.add(new DataModel("Jelly bean", "Android 4.2", "16","July 9, 2012"));
dataModels.add(new DataModel("KitKat", "Android 4.4", "19","October 31, 2013"));
dataModels.add(new DataModel("Lollipop","Android 5.0","21","November 12, 2014"));
dataModels.add(new DataModel("Marshmallow", "Android 6.0", "23","October 5, 2015"));
adapter= new CustomAdapter(dataModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataModel dataModel= dataModels.get(position);
Snackbar.make(view, dataModel.getName()+"\n"+dataModel.getType()+" API: "+dataModel.getVersion_number(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:orientation="vertical"
Android:padding="10dp">
<TextView
Android:id="@+id/name"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_alignParentTop="true"
Android:text="Marshmallow"
Android:textAppearance="?android:attr/textAppearanceSmall"
Android:textColor="@Android:color/black" />
<TextView
Android:id="@+id/type"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_below="@+id/name"
Android:layout_marginTop="5dp"
Android:text="Android 6.0"
Android:textColor="@Android:color/black" />
<ImageView
Android:id="@+id/item_info"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_alignParentEnd="true"
Android:layout_alignParentRight="true"
Android:layout_centerVertical="true"
Android:src="@Android:drawable/ic_dialog_info" />
<LinearLayout
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_centerInParent="true">
<TextView
Android:id="@+id/version_heading"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="API: "
Android:textColor="@Android:color/black"
Android:textStyle="bold" />
<TextView
Android:id="@+id/version_number"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="23"
Android:textAppearance="?android:attr/textAppearanceButton"
Android:textColor="@Android:color/black"
Android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
C'est très simple.
import Android.content.Context;
import Android.content.DialogInterface;
import Android.support.annotation.NonNull;
import Android.support.annotation.Nullable;
import Android.support.v7.app.AlertDialog;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;
import Android.widget.ArrayAdapter;
import Android.widget.Button;
import Android.widget.ImageView;
import Android.widget.TextView;
import Java.util.List;
/**
* Created by Belal on 9/14/2017.
*/
//we need to extend the ArrayAdapter class as we are building an adapter
public class MyListAdapter extends ArrayAdapter<Hero> {
//the list values in the List of type hero
List<Hero> heroList;
//activity context
Context context;
//the layout resource file for the list items
int resource;
//constructor initializing the values
public MyListAdapter(Context context, int resource, List<Hero> heroList) {
super(context, resource, heroList);
this.context = context;
this.resource = resource;
this.heroList = heroList;
}
//this will return the ListView Item as a View
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//we need to get the view of the xml for our list item
//And for this we need a layoutinflater
LayoutInflater layoutInflater = LayoutInflater.from(context);
//getting the view
View view = layoutInflater.inflate(resource, null, false);
//getting the view elements of the list from the view
ImageView imageView = view.findViewById(R.id.imageView);
TextView textViewName = view.findViewById(R.id.textViewName);
TextView textViewTeam = view.findViewById(R.id.textViewTeam);
Button buttonDelete = view.findViewById(R.id.buttonDelete);
//getting the hero of the specified position
Hero hero = heroList.get(position);
//adding values to the list item
imageView.setImageDrawable(context.getResources().getDrawable(hero.getImage()));
textViewName.setText(hero.getName());
textViewTeam.setText(hero.getTeam());
//adding a click listener to the button to remove item from the list
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//we will call this method to remove the selected value from the list
//we are passing the position which is to be removed in the method
removeHero(position);
}
});
//finally returning the view
return view;
}
//this method will remove the item from the list
private void removeHero(final int position) {
//Creating an alert dialog to confirm the deletion
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure you want to delete this?");
//if the response is positive in the alert
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//removing the item
heroList.remove(position);
//reloading the list
notifyDataSetChanged();
}
});
//if response is negative nothing is being done
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//creating and displaying the alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Un exemple plus compact d'adaptateur personnalisé (en utilisant list array comme mes données):
class MyAdapter extends ArrayAdapter<Object> {
public ArrayAdapter(Context context, List<MyObject> objectList) {
super(context, R.layout.my_list_item, R.id.textViewTitle, objectList.toArray());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
TextView title = (TextView) row.findViewById(R.id.textViewTitle);
ImageView icon = (ImageView) row.findViewById(R.id.imageViewAccessory);
MyObject obj = (MyObject) getItem(position);
icon.setImageBitmap( ... );
title.setText(obj.name);
return row;
}
}
Et voici comment l'utiliser:
List<MyObject> objectList = ...
MyAdapter adapter = new MyAdapter(this.getActivity(), objectList);
listView.setAdapter(adapter);
BaseAdapter
est le meilleur adaptateur personnalisé pour listview.
Class MyAdapter extends BaseAdapter{}
et il a beaucoup de fonctions telles que getCount()
, getView()
etc.
public class CustomAdapter extends BaseAdapter{
ArrayList<BookPojo> data;
Context ctx;
int index=0;
public CustomAdapter(ArrayList<BookPojo> data, Context ctx) {
super();
this.data = data;
this.ctx = ctx;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertview, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertview;
if(v==null){
LayoutInflater vi=LayoutInflater.from(ctx);
v=vi.inflate(R.layout.messgeview,null);
}
RelativeLayout rlmessage=(RelativeLayout)v.findViewById(R.id.rlmessgeview);
TextView tvisdn=(TextView)v.findViewById(R.id.tvisdn);
TextView tvtitle=(TextView)v.findViewById(R.id.tvtitle);
TextView tvauthor=(TextView)v.findViewById(R.id.tvauthor);
TextView tvprice=(TextView)v.findViewById(R.id.tvprice);
BookPojo bpj=data.get(position);
tvisdn.setText(bpj.isdn+"");
tvtitle.setText(bpj.title);
tvauthor.setText(bpj.author);
tvprice.setText(bpj.price+"");
if(index%2==0)
{
rlmessage.setBackgroundColor(Color.BLUE);
}
else
{
rlmessage.setBackgroundColor(Color.YELLOW);
}
index++;
return v;
}
}