Android: Custom listview with imageview and textview [duplicate] - android
I want to create a custom adapter for my list view. Is there any article that can walk me through how to create one and also explain how it works?
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;
}
}
This is a class I had used for my project. You need to have a collection of your items which you want to display, in my case it's <Item>. You need to override View getView(int position, View convertView, ViewGroup parent) method.
R.layout.itemlistrow defines the row of the 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>
In the MainActivity define ListViewlike this,
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);
I know this has already been answered... but I wanted to give a more complete example.
In my example, the ListActivity that will display our custom ListView is called OptionsActivity, because in my project this Activity is going to display the different options my user can set to control my app. There are two list item types, one list item type just has a TextView and the second list item type just has a Button. You can put any widgets you like inside each list item type, but I kept this example simple.
The getItemView() method checks to see which list items should be type 1 or type 2. According to my static ints I defined up top, the first 5 list items will be list item type 1, and the last 5 list items will be list item type 2. So if you compile and run this, you will have a ListView that has five items that just contain a Button, and then five items that just contain a TextView.
Below is the Activity code, the activity xml file, and an xml file for each list item type.
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>
This code is easy to understand.
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 has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html
#CommonsWare has written a good explanation of the patterns used in the above example
http://commonsware.com/Android/excerpt.pdf
check this link, in very simple via the convertView, we can get the layout of a row which will be displayed in listview (which is the parentView).
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
}
using the position, you can get the objects of the List<Item>.
Item p = items.get(position);
after that we'll have to set the desired details of the object to the identified form widgets.
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());
}
}
then it will return the constructed view which will be attached to the parentView (which is a ListView/GridView).
Data Model
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;
}
}
Array Adapter
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, false);
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;
}
}
Main Activity
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);
}
}
row_item.xml
<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>
You can take a look at this sample in the official ApiDemos. It shows how to extend BaseAdapter and apply it to a ListView. After that, just look at the reference for BaseAdapter and try to understand what each method does (including the inherited ones) and when/how to use it.
Also, Google is your friend :).
Here is the complete walk through to create a custom adapter for list view step by step -
https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html
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;
}
}
A more compact example of a custom adapter (using list array as my data):
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;
}
}
And this is how to use it:
List<MyObject> objectList = ...
MyAdapter adapter = new MyAdapter(this.getActivity(), objectList);
listView.setAdapter(adapter);
BaseAdapter is best custom adapter for listview.
Class MyAdapter extends BaseAdapter{}
and it has many functions such as getCount(), getView() etc.
It is very 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();
}
}
Source: Custom ListView Android Tutorial
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;
}
}
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONObject;
import java.util.ArrayList;
public class OurteamAdapter extends BaseAdapter {
Context cont;
ArrayList<OurteamModel> llist;
OurteamAdapter madap;
LayoutInflater inflater;
JsonHelper Jobj;
String Id;
JSONObject obj = null;
int position = 0;
public OurteamAdapter(Context c,ArrayList<OurteamModel> Mi)
{
this.cont = c;
this.llist = Mi;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return llist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return llist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
if(convertView == null)
{
LayoutInflater in = (LayoutInflater) cont.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = in.inflate(R.layout.doctorlist, null);
}
TextView category = (TextView) convertView.findViewById(R.id.button1);
TextView title = (TextView) convertView.findViewById(R.id.button2);
ImageView i1=(ImageView) convertView.findViewById(R.id.imageView1);
category.setText(Html.fromHtml(llist.get(position).getGalleryName()));
title.setText(Html.fromHtml(llist.get(position).getGalleryDetail()));
if(llist.get(position).getImagesrc()!=null)
{
i1.setImageBitmap(llist.get(position).getImagesrc());
}
else
{
i1.setImageResource(R.drawable.anandlogo);
}
return convertView;
}
}
Related
use Custome ListView with TextView And CheckBox With Single Selection of CheckBox
Hear i use Custom ListView with TextView and CheckBox. But i want that Single Selection in CheckBox At a time One CheckBox Selected then other one is Deselect using BaseAdapter but This code not Work Properly .. Please Give me Suggestion ..thnks #Override public View getView(final int position, View view, ViewGroup parent) { Integer selected_position = -1; holder = new ViewHolder(); final Items itm = rowItem.get(position); LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (view == null) { view = layoutInflater.inflate(R.layout.activity_custom_list, parent, false); holder.tvItemName = (TextView) view.findViewById(R.id.textView1); holder.check = (CheckBox) view.findViewById(R.id.checkBox1); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.tvItemName.setText(itm.getItems()); if (position == selected_position) holder.check.setChecked(true); else holder.check.setChecked(false); holder.check.setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { if (holder.check.isChecked()) { selected_position = position; } else { selected_position = -1; } notifyDataSetChanged(); } }); return view; }}
use Custom List-View with Text-View And Check-Box With Single Selection of Check Box So many try then finally i got the Solution I hope it is Useful Code to you All... This code Help you to create custom List-view with Text-view and Check-box then you select one check-box and if you select another one the first should automatically be Deselected.....Thank You... activity_main.xml <RelativeLayout 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" tools:context="com.example.listviewdemo2.MainActivity" > <ListView android:id="#+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" /> </RelativeLayout> activity_custom_list.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="#+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.listviewdemo2.CustomListActivity" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#android:color/darker_gray" > <TextView android:id="#+id/textView1" android:layout_width="80dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginTop="4dp" android:layout_weight="0.39" android:textAppearance="?android:attr/textAppearanceMedium" /> <CheckBox android:id="#+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="150dp" android:layout_marginTop="4dp"/> </LinearLayout> </LinearLayout> String.xml <string-array name="name"> <item>Laptop</item> <item>Mobile</item> <item>Desktop</item> <item>TV</item> <item>Pendrive</item> <item>Router</item> <item>Notebook</item> <item>Tablet</item> <item>I-pad</item> <item>Bluetooth</item> <item>HomeTheator</item> </string-array> MainActivity.java String[] ItemName; List<Items> rowItem; ListView list; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rowItem = new ArrayList<Items>(); ItemName = getResources().getStringArray(R.array.name); for(int i = 0 ; i < ItemName.length ; i++) { Items itm = new Items(ItemName[i]); rowItem.add(itm); } list = (ListView) findViewById(R.id.listView1); CustomListActivity adapter = new CustomListActivity(this, rowItem); list.setAdapter(adapter); } Items.java public class Items { private String items; private boolean selected; public Items(String items) { this.items = items; } public String getItems() { return items; } public void setItemName(String name) { this.items = name; } public boolean getSelected() { return selected; } public boolean setSelected(Boolean selected) { return this.selected = selected; }} CustomListActivity.java public class CustomListActivity extends BaseAdapter { Context context; List<Items> rowItem; View listView; boolean checkState[]; ViewHolder holder; public CustomListActivity(Context context, List<Items> rowItem) { this.context = context; this.rowItem = rowItem; checkState = new boolean[rowItem.size()]; } #Override public int getCount() { return rowItem.size(); } #Override public Object getItem(int position) { return rowItem.get(position); } #Override public long getItemId(int position) { return rowItem.indexOf(getItem(position)); } public class ViewHolder { TextView tvItemName; CheckBox check; } #Override public View getView(final int position, View view, ViewGroup parent) { holder = new ViewHolder(); final Items itm = rowItem.get(position); LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (view == null) { listView = new View(context); listView = layoutInflater.inflate(R.layout.activity_custom_list, parent, false); holder.tvItemName = (TextView) listView .findViewById(R.id.textView1); holder.check = (CheckBox) listView.findViewById(R.id.checkBox1); listView.setTag(holder); } else { listView = (View) view; holder = (ViewHolder) listView.getTag(); } holder.tvItemName.setText(itm.getItems()); holder.check.setChecked(checkState[position]); holder.check.setOnClickListener(new OnClickListener() { #Override public void onClick(View arg0) { for(int i=0;i<checkState.length;i++) { if(i==position) { checkState[i]=true; } else { checkState[i]=false; } } notifyDataSetChanged(); } }); return listView; }} Show The Output :-
If you want a custom ListView with single choice CheckBox you can use something like this: https://stackoverflow.com/a/12003125/5778152
CheckBox in custom ListView on Android
I got a custom ListView, and I put three TextView in the List using a custom List Adapter! How I can to add a CheckBox with each List Item and make each CheckBox checked on list item click? <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="#+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textColor="#7a4b9d" android:textSize="15sp" android:textStyle="bold" /> <TextView android:id="#+id/calorie" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="sdf" android:textColor="#ffffff" /> <TextView android:id="#+id/price" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="sdf" android:textColor="#ffffff" /> <CheckBox android:id="#+id/chkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CheckBox" /> </LinearLayout> MainActivity public class Main_Activity extends Fragment implements OnClickListener { private ListView lv; #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub ViewGroup root = (ViewGroup) inflater.inflate(R.layout.main_activity, null); ArrayList<SearchResults> searchResults = GetSearchResults(); final ListView lv = (ListView) root.findViewById(R.id.list_two); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); lv.setTextFilterEnabled(true); lv.setAdapter(new MyCustomBaseAdapter(getActivity(), searchResults)); lv.setOnItemClickListener(new OnItemClickListener() { #Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { boolean result = searchResults.get(position).isSolved(); if (result) { searchResults.get(position).setSolved(false); } else { searchResults.get(position).setSolved(true); } Toast.makeText(getActivity(),"You have chosen: " + " " + fullObject.getPhone(), Toast.LENGTH_SHORT).show(); } }); return root; } private ArrayList<SearchResults> GetSearchResults() { ArrayList<SearchResults> results = new ArrayList<SearchResults>(); SearchResults sr = new SearchResults(); sr.setName("Apple"); sr.setCalorie("35"); sr.setPrice("5"); results.add(sr); return results; } } Custom Base Adapter public class MyCustomBaseAdapter extends BaseAdapter { private static ArrayList<SearchResults> searchArrayList; private LayoutInflater mInflater; public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) { searchArrayList = results; mInflater = LayoutInflater.from(context); } public int getCount() { return searchArrayList.size(); } public Object getItem(int position) { return searchArrayList.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.custom_row_view, null); holder = new ViewHolder(); holder.txtName = (TextView) convertView.findViewById(R.id.name); holder.txtCalorie = (TextView) convertView .findViewById(R.id.calorie); holder.txtPrice = (TextView) convertView.findViewById(R.id.price); holder.chkBox1 = (CheckBox)convertView.findViewById(R.id.chkBox1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.txtName.setText(searchArrayList.get(position).getName()); holder.txtCalorie.setText(searchArrayList.get(position) .getCalorie()); holder.txtPrice.setText(searchArrayList.get(position).getPrice()); holder.chkBox1.setChecked(searchArrayList.get(position).isSolved()); return convertView; } static class ViewHolder { CheckBox chkBox1; TextView txtName; TextView txtCalorie; TextView txtPrice; } Search Results public boolean isSolved() { // TODO Auto-generated method stub return b; } public void setSolved(boolean b) { // TODO Auto-generated method stub this.b = b; }
You will have to define your CheckBox view in custom_row_view.xml file first, <CheckBox android:id="#+id/chkBox1" android:layout_width=... android:layout_height=... /> Then, you wll have to call this reference in your MyCustomBaseAdapter class or in the holder in your case, like CheckBox chkBox1; then, holder.chkBox1 = = (CheckBox)convertView.findViewById(R.id.chkBox1); You can define a boolean value in your SearchResults class which can take care of chkBox check and use holder.chkBox1.setChecked(searchArrayList.get(position).isSolved()); Something on these lines and you will be good to go :) EDIT: Remember to change the value of boolean in searchResult instance on itemClick. boolean result = searchResults.get(position).isSolved(); if (result) { searchResults.get(position).setSolved(false); } else { searchResults.get(position).setSolved(true); } lv.getAdapter().notifyDataSetChanged();
Custom List View with OnClickListener
I have custom ListView layout with a TextView and CheckBox. Everything works fine. What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem. I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well. MAIN ACTIVITY package com.example.smsplanner; public class SMSPlanner extends ListActivity { ListView contactsListView; private String TAG = "SMSPlanner"; CheckBox check; int count; List<ContactInfo> list = new ArrayList<ContactInfo>(); #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ph = new String[3]; phType = new String[3]; LoadContactListFromPhone(); ContactsAdapter contactadAdapter = new ContactsAdapter(this, list); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); setListAdapter(contactadAdapter); } #Override public void onListItemClick(ListView parent, View v, int position, long id) { TextView tx =(TextView)v.findViewById(R.id.firstname); TextView ph =(TextView)v.findViewById(R.id.phone); Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show(); } final class ContactHolder{ TextView txtviewfirstname; CheckBox chkselected; TextView txtviewphone; } void LoadContactListFromPhone() { loadlistandreturns(); } void call() { Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG); toast.show(); } } CUSTOM ADAPTER public class ContactsAdapter extends ArrayAdapter<ContactInfo> { private final Activity context; int resourceid; List<ContactInfo> list = null; public ContactsAdapter(Activity context, List<ContactInfo> list) { super(context, R.layout.contactrow, list); this.context = context; this.list = list; } #Override public View getView(int position, View convertview, ViewGroup viewgroup){ View view = null; if(convertview == null){ LayoutInflater inflater = context.getLayoutInflater(); view = inflater.inflate(R.layout.contactrow, null); ContactHolder holder = new ContactHolder(); holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname); holder.txtviewphone = (TextView)view.findViewById(R.id.phone); holder.chkselected = (CheckBox)view.findViewById(R.id.check); view.setTag(holder); } else{ view = convertview; } ContactHolder holder2 = (ContactHolder) view.getTag(); holder2.txtviewfirstname.setText(list.get(position).firstname); holder2.txtviewphone.setText(list.get(position).phonenumber); holder2.chkselected.setChecked(list.get(position).selected); return view; } final class ContactHolder{ TextView txtviewfirstname; CheckBox chkselected; TextView txtviewphone; } } LAYOUT <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="100" > <RadioGroup android:id="#+id/rgStyle" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="15" android:orientation="vertical" > <TextView android:id="#+id/firstname" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="#+id/phone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:textAppearance="?android:attr/textAppearanceSmall" /> </RadioGroup> <RadioGroup android:id="#+id/rgStyle2" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_weight="85" android:orientation="vertical" > <CheckBox android:id="#+id/check" android:layout_width="fill_parent" android:layout_height="wrap_content" android:checked="false" android:focusable="false" android:focusableInTouchMode="false" > </CheckBox> </RadioGroup> </LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click.... You must implement onItemClickListener() for the ListView.... See this example: http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one : http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as public class ContactsAdapter extends BaseAdapter { ArrayList<ContactInfo> mlist; Context mcontext; public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) { mlist = mchtlist; mcontext = context; } #Override public int getCount() { return mlist.size(); } #Override public Object getItem(int postion) { return mlist.get(postion); } #Override public long getItemId(int position) { return position; } #Override public View getView(int position, View convertview, ViewGroup viewgroup){ View view = null; if(convertview == null){ LayoutInflater inflater = context.getLayoutInflater(); view = inflater.inflate(R.layout.contactrow, null); ContactHolder holder = new ContactHolder(); holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname); holder.txtviewphone = (TextView)view.findViewById(R.id.phone); holder.chkselected = (CheckBox)view.findViewById(R.id.check); setOnClickListener(new OnClickListener() { #Override public void onClick(View arg0) { // to open the selected file in resp // do your work here }}); chkselected .setOnClickListener(new OnClickListener() { #Override public void onClick(View v) { // Toast.makeText(context,// "checked is clicke="+pos, 12).show(); if (chkselected.isChecked()) { // do your work here } else { // do your work here } } }); view.setTag(holder); } else{ view = convertview; } ContactHolder holder2 = (ContactHolder) view.getTag(); holder2.txtviewfirstname.setText(list.get(position).firstname); holder2.txtviewphone.setText(list.get(position).phonenumber); holder2.chkselected.setChecked(list.get(position).selected); return view; } }
Listview, onItemClickListener and EditText
I have a ListView with EditText inside. Actually, when i touch an element of the Listview, the EditText have the focus and the keyboard appeared. Good. The problem is i wanna do something on this EditText throught the listView's onItemClickListener, but seems that my code never enter in this method. I try some setDescendantFocusability to my Listview but don't solve the problem. Thanks a lot. public class NoteAdapter extends BaseAdapter { private ArrayList<String> notes; private LayoutInflater inflater; private Context context; public NoteAdapter(Context context, ArrayList<String> notes) { inflater = LayoutInflater.from(context); this.notes = notes; this.context = context; } public int getCount() { // TODO Auto-generated method stub return notes.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return notes.get(position); } public long getItemId(int id) { // TODO Auto-generated method stub return id; } private class ViewHolder { EditText note; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if(convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.listenote, null); holder.note = (EditText)convertView.findViewById(R.id.note); convertView.setTag(holder); }else { holder= (ViewHolder) convertView.getTag(); } holder.note.setText(notes.get(position)); return convertView; } } my main activity #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); notes = new ArrayList<String>(); for(int i=0; i< 10; i++) notes.add("note"+i); EditTextSelected = null; adapter = new NoteAdapter(this, notes); lv1 = ((ListView)findViewById(R.id.listeNote)); lv1.setAdapter(adapter); lv1.setClickable(true); lv1.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, int position, long id) { Toast t = Toast.makeText(FastItActivity.this, "hello", 200); t.show(); } }); listenote.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout android:id="#+id/widget1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <EditText android:id="#+id/note" android:textColor="#color/black" android:textSize="12dp" android:layout_width="wrap_content" android:layout_height="40dp" android:padding="5dp" android:inputType="textMultiLine" android:scrollHorizontally="false" android:gravity="top|left" android:ems="10" android:layout_margin="10dp" android:background="#drawable/fond_note" /> </TableLayout> main.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout android:id="#+id/widget1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" android:background="#drawable/wooden_top" > <ListView android:id="#+id/listeNote" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:background="#android:color/transparent" android:cacheColorHint="#00000000" android:isScrollContainer="false" android:divider="#00000000" > </ListView> </TableLayout>
Move your modifications from ListView's onItemClickListener to your EditText's onClickListener In NoteAdapter's getView: holder.note = (EditText)convertView.findViewById(R.id.note); holder.note.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { //do something } }); or try this: holder.note.setOnFocusListener(new View.OnFocusListener(){ #Override public void onFocus(){ //do something } } getView method has position parameter so you'll be able to distinguish what EditText was clicked (if you need different actions with different EditTexts)
This article is pretty long but towards the middle/end he demonstrates an interactive listview which is exactly what you need. http://www.vogella.de/articles/AndroidListView/article.html If you could post some code that would help.
I was trying to solve a similar problem: which item in a list was selected when you embed several views in list item?! I refuse to create a new listener for each item in the list. I can't imagine that would scale well on such a resource constrained platform. But, I found you can solve this problem by specializing EditText to set and retrieve the selected index in onClick. Define your specialization: package userInterface; import android.content.Context; import android.util.AttributeSet; import android.widget.EditText; public class IndexedEditText extends EditText { public int listIndex; public IndexedEditText(Context context) { super(context); } public IndexedEditText(Context context, AttributeSet attrs) { super(context, attrs); } public IndexedEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } } Replace your EditText for your specialized class in the list item XML declaration. Be sure to get the path to your new class right (in my case it's userInterface.IndexedEditText). <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <userInterface.IndexedEditText android:id="#+id/et_first_item" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:hint="#string/select" android:inputType="none" /> <!-- other views --> </RelativeLayout> Set listIndex in getView, and set your OnClickListener for each IndexedEditText instance: public abstract class EditTextPairArrayAdapter <T> extends ArrayAdapter<T> { LayoutInflater inflater; static class ViewHolder { private WeakReference<IndexedEditText> name; private WeakReference<EditText> notes; public ViewHolder(IndexedEditText tv, EditText et) { name = new WeakReference<IndexedEditText>(tv); notes = new WeakReference<EditText>(et); } } int textViewId; int editTextId; int listItemId; List<T> list = null; WeakReference<Context> contextRef; //context is Activity that instantiates this array adapter //resourceId is the layout xml ID for your special row //textViewResourceId is any TextView ID in your special row xml def //editTextResourceId means nothing in this context //objects is the initial list of objects to present in UI public EditTextPairArrayAdapter(Context context, int resourceId, int textViewResourceId, int editTextResourceId, List<T> objects) { super(context, resourceId, textViewResourceId, objects); this.listItemId = resourceId; this.textViewId = textViewResourceId; this.editTextId= editTextResourceId; this.list = objects; this.contextRef = new WeakReference<Context>(context); } #Override public View getView(int position, View convertView, ViewGroup viewGroup) { View view = null; ViewHolder viewHolder = null; if (convertView == null) { if(inflater == null) inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(listItemId, null); IndexedEditText text = (IndexedEditText)view.findViewById(textViewId); EditText notes = (EditText) view.findViewById(editTextId); text.listIndex = position; //Special sauce if(contextRef != null && contextRef.get() != null && (contextRef.get() instanceof View.OnClickListener)) { text.setOnClickListener((View.OnClickListener) contextRef.get()); } viewHolder = new ViewHolder(text, notes); view.setTag(viewHolder); } else { view = convertView; viewHolder = (ViewHolder) convertView.getTag(); } Titem = this.getItem(position); if(item != null) { //special sauce } return view; } //add abstract methods for implementations to define special sauce } Finally, in your Activity that implements OnClickListener: public void onClick(View v) { if(v instanceof IndexedEditText) { Object obj = myList.get(((IndexedEditText)v).listIndex); //do stuff with obj } }
The solution I found is to superimpose an EditText with a TextView and alternate gone/visible on both so that the EditText stops inducing bugs when hidden.
Custom Adapter for List View
I want to create a custom adapter for my list view. Is there any article that can walk me through how to create one and also explain how it works?
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; } } This is a class I had used for my project. You need to have a collection of your items which you want to display, in my case it's <Item>. You need to override View getView(int position, View convertView, ViewGroup parent) method. R.layout.itemlistrow defines the row of the 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> In the MainActivity define ListViewlike this, 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);
I know this has already been answered... but I wanted to give a more complete example. In my example, the ListActivity that will display our custom ListView is called OptionsActivity, because in my project this Activity is going to display the different options my user can set to control my app. There are two list item types, one list item type just has a TextView and the second list item type just has a Button. You can put any widgets you like inside each list item type, but I kept this example simple. The getItemView() method checks to see which list items should be type 1 or type 2. According to my static ints I defined up top, the first 5 list items will be list item type 1, and the last 5 list items will be list item type 2. So if you compile and run this, you will have a ListView that has five items that just contain a Button, and then five items that just contain a TextView. Below is the Activity code, the activity xml file, and an xml file for each list item type. 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>
This code is easy to understand. 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 has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html #CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf
check this link, in very simple via the convertView, we can get the layout of a row which will be displayed in listview (which is the parentView). View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.itemlistrow, null); } using the position, you can get the objects of the List<Item>. Item p = items.get(position); after that we'll have to set the desired details of the object to the identified form widgets. 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()); } } then it will return the constructed view which will be attached to the parentView (which is a ListView/GridView).
Data Model 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; } } Array Adapter 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, false); 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; } } Main Activity 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); } } row_item.xml <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>
You can take a look at this sample in the official ApiDemos. It shows how to extend BaseAdapter and apply it to a ListView. After that, just look at the reference for BaseAdapter and try to understand what each method does (including the inherited ones) and when/how to use it. Also, Google is your friend :).
Here is the complete walk through to create a custom adapter for list view step by step - https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html 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; } }
A more compact example of a custom adapter (using list array as my data): 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; } } And this is how to use it: List<MyObject> objectList = ... MyAdapter adapter = new MyAdapter(this.getActivity(), objectList); listView.setAdapter(adapter);
BaseAdapter is best custom adapter for listview. Class MyAdapter extends BaseAdapter{} and it has many functions such as getCount(), getView() etc.
It is very 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(); } } Source: Custom ListView Android Tutorial
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; } }
import android.app.Activity; import android.content.Context; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONObject; import java.util.ArrayList; public class OurteamAdapter extends BaseAdapter { Context cont; ArrayList<OurteamModel> llist; OurteamAdapter madap; LayoutInflater inflater; JsonHelper Jobj; String Id; JSONObject obj = null; int position = 0; public OurteamAdapter(Context c,ArrayList<OurteamModel> Mi) { this.cont = c; this.llist = Mi; } #Override public int getCount() { // TODO Auto-generated method stub return llist.size(); } #Override public Object getItem(int position) { // TODO Auto-generated method stub return llist.get(position); } #Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } #Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if(convertView == null) { LayoutInflater in = (LayoutInflater) cont.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = in.inflate(R.layout.doctorlist, null); } TextView category = (TextView) convertView.findViewById(R.id.button1); TextView title = (TextView) convertView.findViewById(R.id.button2); ImageView i1=(ImageView) convertView.findViewById(R.id.imageView1); category.setText(Html.fromHtml(llist.get(position).getGalleryName())); title.setText(Html.fromHtml(llist.get(position).getGalleryDetail())); if(llist.get(position).getImagesrc()!=null) { i1.setImageBitmap(llist.get(position).getImagesrc()); } else { i1.setImageResource(R.drawable.anandlogo); } return convertView; } }