I have a main activity that has a Recyclerview, It displays a list image and a text as the title.
In the main activity I have three array lists; one for the image, one for its title and the last one "array" for a String array.
I am passing the R.array.id as a string into the next activity On Click of an item in the MainActivity. I send the image, title, and the array.
In the second Activity, where I check for incoming intent, Assign them to strings.
String imageUrl = getIntent().getStringExtra("image_url");
String imageName = getIntent().getStringExtra("image_name");
String array= getIntent().getStringExtra("array_id");
Then I have called setArray(array) and then inside the function, I got stuck.
private void setArray(String array) {
// Stuck here
}
I don't know what to do. I have set a ListView in the second layout
and found this code on this site.
ListView lv = (ListView) findViewById(R.id.extView);
ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this, R.array.id, android.R.layout.simple_list_item_1);
lv.setAdapter(aa);
Which works, if I have a set the source to a static array id but how do I set it the string I receive?
Tried getString(array), which did not work. I also need to set an onClick listener to the items.
For displaying an array in a ListView, you need to have a custom adapter. The ArrayAdapter that you are currently using, is the native adapter for showing a list provided by Android SDK. However, you need a custom class if you need to show the ListView which populates the items dynamically from your array.
In order to do that, you need to have a custom adapter class like the following.
public class ListAdapter extends ArrayAdapter<String> {
private int resourceLayout;
private Context mContext;
public ListAdapter(Context context, int resource, List<String> 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);
}
String p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.id);
tt1.setText(p.getId());
}
return v;
}
}
Now you need a layout which indicates each item of your list. For example, the name of your layout is list_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:height="40sp" />
</LinearLayout>
Now in your second Activity, you need to initialize the adapter and set the adapter in your ListView like the following. Please note that, as the adapter takes a List, you need to convert your array string from a String to a List and then pass it to the adapter.
// I assume, the String is comma separated, which indicates the array.
List<String> arrayList = Arrays.asList(array.split("\\s*,\\s*"));
ListView lv = (ListView) findViewById(R.id.extView);
ListAdapter customAdapter = new ListAdapter(this, R.layout.list_item, arrayList);
lv.setAdapter(customAdapter);
Hope that helps!
Related
I am trying to load images to imageview in my ListAdapter. However while I am passing 10 thumbnail images to listAdapter and set them in imageview, only 1 or none is visible in imageview. As I understand from docs, I dont need to use any asyntask, since picasso library has already working asyntask. Could you please help me how I can handle this issue?
// Calling CustumListAdapter like this;
CustomListAdapter customListAdapter = new CustomListAdapter(this, resultArrayList);
listView = (ListView) findViewById(R.id.listview_score);
listView.setAdapter(customListAdapter)
// And here is my CustomListAdapter class
public class CustomListAdapter extends ArrayAdapter<String> {
private ArrayList<String> resultContent;
//private Integer[] imageid;
private Activity context;
public CustomListAdapter(Activity context, ArrayList<String> resultContent) {
super(context, R.layout.activity_ident_result2, resultContent);
this.context = context;
this.resultContent = resultContent;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.activity_ident_result2, null, true);
if (position % 2 == 0) {
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textView_score);
textViewName.setText(resultContent.get(position));
ImageView imageView = (ImageView) listViewItem.findViewById(R.id.imageView_score);
//imageView.setImageBitmap(IdentResultActivity.splittedBitmaps.get(position + 1));
Picasso.with(this.context).load(resultContent.get(position + 1)).into(imageView);
}
return listViewItem;
}
}
EDIT:
I used .placeholder(R.drawble.progress) and I can see one image placed without problem, rest are progress.png
EDIT2:
Here is my imageView xml file;
<ImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:id="#+id/imageView_score" />
I believe the parameters of inflater.inflate should be (R.layout.activity_ident_result2, parent, false)
U need to create loop for adding every image to [] and then u need to show it. Becouse of ur posted code u adding just one image.
I am trying to populate a listview with custom made objects. I am using an
adapter to use the listview class. The following is the code I use to use the adapter.
adapter = new SearchListAdapter(this, values);
expListView = (ListView) findViewById(R.id.SearchList);
setListAdapter(adapter);
In the SearchListAdapter class I have the following code:
public class SearchListAdapter extends ArrayAdapter<String>
{
private Context context;
private ArrayList<String> values;
public SearchListAdapter(Context context, ArrayList<String> UsernameValues) {
super(context, R.layout.search_contact, UsernameValues);
this.context = context;
this.values = UsernameValues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.search_contact, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
for(String Index : values)
{
textView.setText(Index);
}
return rowView;
}
}
I can see that the setListAdapter is working (I assume), as it is passing the information into the SearchListAdapter, but when the getView tries to populate the list, it just enters the last String value from the ArrayList in every single element in the list. What am I missing to make it so every single element corresponds to a value in the ArrayList? Any help is appreciated, thanks.
Your code
for(String Index : values)
{
textView.setText(Index);
}
is actually iterating over your complete data List and setting each value at every iteration. So, after the last iteration, every textView is left with the last value in your adapter's backing List.
What you need is to only set that value that corresponds to the current row position of your ListView in your UsernameValues list.
textView.setText(values.get(position));
I have made a ListView which is populated with elements of an ArrayList. I do not have an XML file with this ListView, it is only in Java. Given this, how would I change the background color of the ListView as well as change the color of the text of the ListView?
This is the code for the ListView:
setListAdapter(new ArrayAdapter<String>(CollegeList.this, android.R.layout.simple_list_item_1, nameList));
In case you want to customize each line of the listview you have to use a custom adapter with custom listview item. Then you can use the "getView" Method to catch each item and position to change colors.
Here is a sample:
public class ListViewAdapter extends ArrayAdapter<Item> {
private Context context;
private int itemResourceId;
private ArrayList<Item> items;
public ListViewAdapter(Context context, int layoutId, ArrayList<Item> items) {
super(context, layoutId, items);
this.context = context;
this.itemResourceId = layoutId;
this.items = items;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder = null;
if (view == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(itemResourceId, null);
holder.listItem = (TextView) view.findViewById(R.id.item);
view.setTag(holder);
}
else
holder = (ViewHolder) view.getTag();
if (position % 2 == 0)
view.setBackgroundColor(context.getResources().getColor(R.color.listItemEven));
else
view.setBackgroundColor(context.getResources().getColor(R.color.listItemOdd));
Item item = items.get(position);
holder.listItem.setText((position+1) + ". " + item.sTitle);
return view;
}
static class ViewHolder {
TextView listItem;
}
}
android.R.layout.simple_list_item_1
You have to add an extra parameter to your ArrayAdapter, this will be a CUSTOM XML OF YOUR OWN and the next one will be a textview that is inside that custom layout, that way the array adapter will know which layout to fill and which textview needs to show the data you want to show.
from that xml you can modify background and color. will look something like this:
setListAdapter(new ArrayAdapter<String>(CollegeList.this, R.layout.your_custom_layout, R.id.the-text-view-in-that-layout, nameList));
You can get the xml for simple_list_item_1 here. You can copy it to your project and modify it, just change the code for your listview to setListAdapter(new ArrayAdapter<String>(CollegeList.this, R.layout.simple_list_item_1, nameList)); You can also create one yourself, since simple_list_item_1 is nothing but a textview. Just make sure that the id is android:id="#android:id/text1" otherwise it won't work with the default adapter.
I was just asking myself if there was a way of making a ListView without any texts. I've only found ListViews with images + texts, and that exactly what i dont want. I just want to add a lot of images like in a list and don't want to make it with ImageView because that makes my app crash. Also, i dont want my app to lag. Thanks!
this is what i got in my activity_main.xml
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
and i found this from another post that actually helped me, but it doesnt display all images
public class MainActivity extends Activity {
// Array of integers points to images stored in /res/drawable-hdpi/
int[] vehs = new int[]{
R.drawable.veh1,
R.drawable.veh2,
R.drawable.veh3,
R.drawable.veh4,
R.drawable.veh5,
R.drawable.veh6,
R.drawable.veh7,
R.drawable.veh8,
R.drawable.veh9,
R.drawable.veh10,
R.drawable.veh11,
R.drawable.veh12,
R.drawable.veh13,
R.drawable.veh14,
R.drawable.veh15,
R.drawable.veh16,
R.drawable.veh17,
R.drawable.veh18,
R.drawable.veh19,
R.drawable.veh20,
R.drawable.veh21,
R.drawable.veh22,
R.drawable.veh23,
R.drawable.veh24,
R.drawable.veh25,
R.drawable.veh26,
R.drawable.veh27,
R.drawable.veh28,
R.drawable.veh29,
R.drawable.veh30,
R.drawable.veh31,
R.drawable.veh32,
R.drawable.veh33,
R.drawable.veh34,
R.drawable.veh35,
R.drawable.veh36,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("vehs", Integer.toString(vehs[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "vehs","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.vehs,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
Didn't edit all the code, so you might find some things confusing xD
The way ListView displays data is by using an adapter. The adapter takes your data, inserts it into a custom view, and then adds it to the list.
To build a fast images ListView, the first thing you'd want to do is to add Picasso to your project. This library will automatically download and cache your images, handle ImageView recycling, and more.
The next thing you'd want to do is to write your item view. If you want an images-only list, the view could be as simple as:
<!-- res/layout/list_item.xml -->
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight" />
Next, you want to create your adapter. It accepts a List<String> of image URLs as an input, builds the items and inserts them to the ListView.
public class ImageListAdapter extends ArrayAdapter<String> {
List<String> items;
public ImageListAdapter(Context context, int resource, List<String> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_item, null);
}
Picasso.with(getContext())
.load(items.get(position))
.into((ImageView) convertView);
return convertView;
}
}
Read the Picasso library documentation if you want to add more options such as image placeholders, transformations, and more.
Finally, to use the adapter on your ListView, add this to your activity's onCreate method:
List<String> images = new ArrayList<String>();
images.add("http://hometowncolumbia.files.wordpress.com/2007/12/lol-cats-dont-look-behind-cat.jpg");
images.add("http://i232.photobucket.com/albums/ee245/topswing/cat-lol.jpg");
listView = (ListView)findViewById(R.id.myListView);
listView.setAdapter(new ImageListAdapter(this, R.layout.list_item, images))
In a real application though, you'd probably want to load the image list from your server. You'd need to use an AsyncTask for that.
Don't make things difficult, the solution is simple in the classic 3 steps
Step 1:
Make a RelativeLayout in XML. Move the image to desired position (always to center, but you can choose if left or right) and change layout_height to wrap_content
Step 2:
Create a custom adapter for ListView, if you do this, you'll be able to all any layout as an item
public class ImagesAdapter extends ArrayAdapter<String> {
private Activity mContext;
private ArrayList<Bitmap> mImages;
public ImagesAdapter(Activity context, ArrayList<String> listOfValues, ArrayList<Bitmap> images) {
//The listOfValues is used when you make item click to get value
//Each image must to have a text value
super(context, R.layout.yourlayout, listOfValues);
mContext = context;
mImages = images;
}
#Override
public void getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = mContext.getLayoutInflater();
View returnView = inflater.inflate(R.layout.yourlayout, null);
ImageView imageView = (ImageView) returnView.findViewById(R.id.yourimageid);
imageView.setImageBitmap(mImages.get(position));
return returnView;
}
}
Step 3:
Implement in your code
ImagesAdapter adapter = new ImagesAdapter(this, myList, myImages);
mylistView.setAdapter(adapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//volov = Values Of ListOfValues
String volov = (String) myListView.getItemPosition(position);
Log.i(TAG, "listOfValues is useful " + volov);
}
});
I want my ListView to contain buttons, but setting the button's xml property, onClick="myFunction" and then placing a public void myFunction(android.view.View view) method in the activity causes an NoSuchMethodException (the stack trace is null) to be thrown, as although the onclick listener is there, it doesn't fire myFunction(...) and cause the activity to close.
How do I create a custom Adapter that connects a View.OnClickListener to a button on each row of a ListView?
My ListView is created as follows...
[activity.java content..]
public void myFunction(android.view.View view)
{
//Do stuff
}
[activity.xml content..]
<LinearLayout xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".FrmCustomerDetails" >
<ListView android:id="#+id/LstCustomerDetailsList" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:clickable="true" android:clipChildren="true" android:divider="#null" android:dividerHeight="0dp" android:fastScrollEnabled="true" android:footerDividersEnabled="false" android:headerDividersEnabled="false" android:requiresFadingEdge="vertical" android:smoothScrollbar="true" />
</LinearLayout>
[activity_row_item.xml content..]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="#+id/Llt" android:layout_width="match_parent" android:layout_height="match_parent" >
<Button android:id="#+id/Btn" android:text="Click me" android:onClick="myFunction" />
</LinearLayout>
Here is how to create the custom Adapter, connecting View.OnClickListener to a ListView with a button per row...
1. Create a layout for a typical row
In this case, the row is composed of three view components:
name (EditText)
value (EditText:inputType="numberDecimal")
delete (Button)
Xml
pay_list_item.xml layout is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/pay_name"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"
android:hint="Name" />
<EditText
android:id="#+id/pay_value"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:inputType="numberDecimal"
android:text="0.0" />
<Button
android:id="#+id/pay_removePay"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:text="Remove Pay"
android:onClick="removePayOnClickHandler" />
</LinearLayout>
Note: the button has onClick handler defined in xml layout file, because we want to refer its action to a specific list item.
Doing this means that the handler will be implemented in Activity file and each button will know which list item it belongs to.
2. Create list item adapter
This is the java class that is the controller for pay_list_item.xml.
It keeps references for all of its views, and it also puts these references in tags, extending the ArrayAdapter interface.
The Adapter:
public class PayListAdapter extends ArrayAdapter<Payment> {
private List<Payment> items;
private int layoutResourceId;
private Context context;
public PayListAdapter(Context context, int layoutResourceId, List<Payment> items) {
super(context, layoutResourceId, items);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
PaymentHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PaymentHolder();
holder.Payment = items.get(position);
holder.removePaymentButton = (ImageButton)row.findViewById(R.id.pay_removePay);
holder.removePaymentButton.setTag(holder.Payment);
holder.name = (TextView)row.findViewById(R.id.pay_name);
holder.value = (TextView)row.findViewById(R.id.pay_value);
row.setTag(holder);
setupItem(holder);
return row;
}
private void setupItem(PaymentHolder holder) {
holder.name.setText(holder.Payment.getName());
holder.value.setText(String.valueOf(holder.Payment.getValue()));
}
public static class PaymentHolder {
Payment Payment;
TextView name;
TextView value;
ImageButton removePaymentButton;
}
}
Here we list the Payment class items.
There are three most important elements here:
PayListAdapter constructor: sets some private fields and calls superclass constructor. It also gets the List of Payment objects. Its implementation is obligatory.
PaymentHolder: static class that holds references to all views that I have to set in this list item. I also keep the Payment object that references to this particular item in list. I set it as tag for ImageButton, that will help me to find the Payment item on list, that user wanted to remove
Overriden getView method: called by superclass. Its goal is to return the single List row. We create its fields and setup their values and store them in static holder. Holder then is put in row’s tag element. Note that there is a performance issue, as the row is being recreated each time it is displayed. I used to add some flag in holder like isCreated, and set it to true after row was already created. then you can add if statement and read tag’s holder instead of creating it from scratch.
Payment.java is quite simple as for now and it looks a bit like BasicNameValuePair:
public class Payment implements Serializable {
private String name = "";
private double value = 0;
public Payment(String name, double value) {
this.setName(name);
this.setValue(value);
}
...
}
There are additional gets and sets for each private field not shown.
3. Add ListView to the activity layout xml file
In its simpliest form, it will be enough to add this view to activity layout:
<ListView
android:id="#+id/EnterPays_PaysList"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
4. Set up adapter to this list view in Activity Java code
In order to display items in ListView you need to set up its adapter and map it to some other ArrayList of Payment objects (as I am extending an Array adapter here). Here is code that is responsible for binding adapter to editPersonData.getPayments() ArrayList:
PayListAdapter adapter = new PayListAdapter(AddNewPerson.this, R.layout.pay_list_item, editPersonData.getPayments());
ListView PaysListView = (ListView)findViewById(R.id.EnterPays_PaysList);
PaysListView.setAdapter(adapter);
5. Adding / removing items to ListView (and its adapter)
Adapter is handled just like any other ArrayList, so adding new element to it is as simple as:
Payment testPayment = new Payment("Test", 13);
adapter.add(testPayment);
adapter.remove(testPayment);
6. Handle Remove Payment button click event
In an activity’s code, where ListView is displayed, add public method that will handle remove button click action. The method name has to be exactly the same as it was in pay_list_item.xml:
android:onClick="removePayOnClickHandler"
The method body is as follows:
public void removePayOnClickHandler(View v) {
Payment itemToRemove = (Payment)v.getTag();
adapter.remove(itemToRemove);
}
The Payment object was stored in ImageButton’s Tag element. Now it is enough to read it from Tag, and remove this item from the adapter.
7. Incorporate remove confirmation dialog window
Probably you need also make sure that user intentionally pressed the remove button by asking him additional question in confirmation dialog.
Dialogue
a) Create dialog’s id constant
This is simply dialog’s ID. it should be unique among any other dialog window that is handled by current activity. I set it like that:
protected static final int DIALOG_REMOVE_CALC = 1;
protected static final int DIALOG_REMOVE_PERSON = 2;
b) Build dialog
I use this method to build dialog window:
private Dialog createDialogRemoveConfirm(final int dialogRemove) {
return new AlertDialog.Builder(getApplicationContext())
.setIcon(R.drawable.trashbin_icon)
.setTitle(R.string.calculation_dialog_remove_text)
.setPositiveButton(R.string.calculation_dialog_button_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
handleRemoveConfirm(dialogRemove);
}
})
.setNegativeButton(R.string.calculation_dialog_button_cancel, null)
.create();
}
AlertDialog builder pattern is utilized here. I do not handle NegativeButton click action – by default the dialog is just being hidden. If dialog’s confirm button is clicked, my handleRemoveConfirm callback is called and action is performed based on dialog’s ID:
protected void handleRemoveConfirm(int dialogType) {
if(dialogType == DIALOG_REMOVE_PERSON){
calc.removePerson();
}else if(dialogType == DIALOG_REMOVE_CALC){
removeCalc();
}
}
c) Show Dialog
I show dialog after my remove button click. The showDialog(int) is Android’s Activity’s method:
OnClickListener removeCalcButtonClickListener = new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_REMOVE_CALC);
}
};
the showDialog(int) method calls onCreateDialog (also defined in Activity’s class). Override it and tell your app what to do if the showDialog was requested:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_REMOVE_CALC:
return createDialogRemoveConfirm(DIALOG_REMOVE_CALC);
case DIALOG_REMOVE_PERSON:
return createDialogRemoveConfirm(DIALOG_REMOVE_PERSON);
}
}
Take a look at this blog post I wrote on exactly this matter:
Create custom ArrayAdapter
There are comments that explain every action I make in the adapter.
Here is the explanation in short:
So lets for example take a row where you want to place a CheckBox, ImageView
and a TextView while all of them are clickable. Meaning that you can click the
row it self for going to another Actvity for more details on the row, check its
CheckBox or press the ImageView to perform another operation.
So what you should do is:
1. First create an XML layout file for your ListView row:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbCheckListItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp" />
<TextView
android:id="#+id/tvItemTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item string" />
<ImageView
android:id="#+id/iStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="#drawable/ic_launcher"
android:src="#drawable/ic_launcher" />
</LinearLayout>
2. Second in your java code define a ViewHolder, a ViewHolder
is designed to hold the row views and that way operating more quickly:
static class ViewHolder
{
TextView title;
CheckBox checked;
ImageView changeRowStatus;
}
3. Now we have to define CustomArrayAdapter, using the array adapter
we can define precisely what is the desired output for each row based on the content of this
row or it’s position. We can do so by overriding the getView method:
private class CustomArrayAdapter extends ArrayAdapter<RowData>
{
private ArrayList<RowData> list;
//this custom adapter receives an ArrayList of RowData objects.
//RowData is my class that represents the data for a single row and could be anything.
public CustomArrayAdapter(Context context, int textViewResourceId, ArrayList<RowData> rowDataList)
{
//populate the local list with data.
super(context, textViewResourceId, rowDataList);
this.list = new ArrayList<RowData>();
this.list.addAll(rowDataList);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
//creating the ViewHolder we defined earlier.
ViewHolder holder = new ViewHolder();)
//creating LayoutInflator for inflating the row layout.
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//inflating the row layout we defined earlier.
convertView = inflator.inflate(R.layout.row_item_layout, null);
//setting the views into the ViewHolder.
holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
holder.changeRowStatus = (ImageView) convertView.findViewById(R.id.iStatus);
holder.changeRowStatus.setTag(position);
//define an onClickListener for the ImageView.
holder.changeRowStatus.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(activity, "Image from row " + position + " was pressed", Toast.LENGTH_LONG).show();
}
});
holder.checked = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
holder.checked.setTag(position);
//define an onClickListener for the CheckBox.
holder.checked.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//assign check-box state to the corresponding object in list.
CheckBox checkbox = (CheckBox) v;
rowDataList.get(position).setChecked(checkbox.isChecked());
Toast.makeText(activity, "CheckBox from row " + position + " was checked", Toast.LENGTH_LONG).show();
}
});
//setting data into the the ViewHolder.
holder.title.setText(RowData.getName());
holder.checked.setChecked(RowData.isChecked());
//return the row view.
return convertView;
}
}
4. Now you need to set this adapter, as the adapter of your ListView.
this ListView can be created in java or using an XML file, in this case I’m using a list that was
defined in the XML file using the “list” id:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
ListView list = (ListView)findViewById(R.id.list);
CustomArrayAdapter dataAdapter = new CustomArrayAdapter(this, R.id.tvItemTitle, rowDataList);
list.setAdapter(dataAdapter);
}
5. Finally if we want to be able to press the row it self and not only a certain view in it
we should assign an onItemClickListener to the ListView:
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
Toast.makeText(activity, "row " + position + " was pressed", Toast.LENGTH_LONG).show();
}
});
First, the way of adding listeners in xml using onClick="function" is deprecated. You need a ViewHolder class to link the button in the xml to your java code. Then you can implement onClickListener for that.
Inside your getView() implementation of CustomAdapter, you can try like below.
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.xxxxx, null);
holder = new ViewHolder();
holder.invite = (Button) convertView.findViewById(R.id.button);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleClick(pos);
}
});
}
class ViewHolder {
Button button;
}