OnClickListener Inside Adapter View - android

In my activity I am displaying a list of data, each row has an edit and delete button. The listeners for these buttons are defined inside the listviews adapter.
I have implemented a custom array adapter:
public class SalesArrayAdapter extends ArrayAdapter<SaleModel> {
private Context context;
private int altColour;
private SaleModel sale;
private int position;
private ArrayList<SaleModel> sales;
private static class ViewHolder{
RelativeLayout container;
TextView tvId;
TextView tvDate;
TextView tvBusNo;
TextView tvDriver;
TextView tvNoOfTrips;
TextView tvTotalExpenditure;
TextView tvTotal;
TextView tvAmountReceived;
TextView tvStatus;
TextView tvReceiptCode;
ImageButton btnEdit;
ImageButton btnRemove;
}
public SalesArrayAdapter(#NonNull Context context, #NonNull ArrayList<SaleModel> sales) {
super(context, R.layout.row_sales, sales);
//this.getContext() = getContext();
//this.sales = sales;
}
#NonNull
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
// Get the data item for this position
sale = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_sales, parent, false);
viewHolder.container = (RelativeLayout) convertView.findViewById(R.id.row_sales_ll_container);
viewHolder.tvId = (TextView) convertView.findViewById(R.id.row_sales_tv_id);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.row_sales_tv_date);
viewHolder.tvDriver = (TextView) convertView.findViewById(R.id.row_sales_tv_driver);
viewHolder.tvNoOfTrips = (TextView) convertView.findViewById(R.id.row_sales_tv_total_no_of_trips);
viewHolder.tvTotalExpenditure = (TextView) convertView.findViewById(R.id.row_sales_tv_total_expenditure);
viewHolder.tvTotal = (TextView) convertView.findViewById(R.id.row_sales_tv_total);
viewHolder.tvAmountReceived = (TextView) convertView.findViewById(R.id.row_sales_tv_amount_received);
viewHolder.tvStatus = (TextView) convertView.findViewById(R.id.row_sales_tv_status);
viewHolder.tvReceiptCode = (TextView) convertView.findViewById(R.id.row_sales_tv_receipt_code);
viewHolder.btnEdit = (ImageButton) convertView.findViewById(R.id.row_sales_btn_edit);
viewHolder.btnRemove = (ImageButton) convertView.findViewById(R.id.row_sales_btn_trash);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
if (altColour == 0) {
viewHolder.container.setBackgroundColor(Color.parseColor("#FFFFFF"));
altColour = 1;
} else {
viewHolder.container.setBackgroundColor(Color.parseColor("#EFEFEF"));
altColour = 0;
}
viewHolder.tvId.setText(String.valueOf(sale.getId()));
viewHolder.tvDate.setText(sale.getDate());
viewHolder.tvDriver.setText(sale.getDriver());
double totalTripsAmount = 0;
for(int c = 0; c < sale.getTrips().length(); c++) {
try {
totalTripsAmount += sale.getTrips().getJSONObject(c).getDouble("trip_amount");
} catch (JSONException e) {
e.printStackTrace();
}
}
viewHolder.tvNoOfTrips.setText("GHS "+totalTripsAmount);
double totalExpenditureAmount = 0;
for(int c = 0; c < sale.getExpenditure().length(); c++) {
try {
totalExpenditureAmount += sale.getExpenditure().getJSONObject(c).getDouble("amount");
} catch (JSONException e) {
e.printStackTrace();
}
}
viewHolder.tvTotalExpenditure.setText("GHS "+totalExpenditureAmount);
viewHolder.tvTotal.setText("GHS "+sale.getTotal());
viewHolder.tvAmountReceived.setText("GHS "+sale.getAmountReceived());
viewHolder.tvStatus.setText(sale.getIsPending() == 1 ? "Pending" : "Complete");
viewHolder.tvReceiptCode.setText(sale.getReceiptCode());
viewHolder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent editSaleIntent = new Intent(getContext(), EditSaleActivity.class);
editSaleIntent.putExtra("sale", sale.toJson().toString());
((Activity) getContext()).startActivityForResult(editSaleIntent, 800);
}
});
viewHolder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = new Integer(getPosition(sale));
removeSale(pos);
}
});
// Return the completed view to render on screen
return convertView;
}
private void removeSale(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Confirm");
builder.setMessage("Are you sure you want to delete?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Log.i("btnYes", "works");
SalesRequest salesRequest = new SalesRequest(getContext());
remove(getItem(position));
notifyDataSetChanged();
salesRequest.remove(getItem(position).getId(), mTrashOnSuccessListener, mTrashOnErrorListener);
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private Response.Listener<JSONObject> mTrashOnSuccessListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//
}
};
Response.ErrorListener mTrashOnErrorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Utils.showNetworkResponse(getContext(), error);
}
};
}
Now my issue is when I click the delete or edit button for any item being displayed it always picks the position or id of the last item being display in the listview.
For example if I wanted to delete the second item in the listview with a position of 1 it would pick the last item being displayed with a position of 10.
I've tried soo many things and made soo many changes but nothing has worked so far, this is my final code.

You can add a tag in a button. Tag the current position to the button when getView method is called every time. When the button is clicked get the tage of the button and it will return the updated value/position of the button. And do what you want to do with that current position in call back of that button click. Hope that helps
Adding more information
you have this line of code
viewHolder.btnEdit
this is the edit button . Now you should add a tag to this button using below code. You need to use below code after else clause of Viewholder object initialization.
viewHolder.btnEdit.setTag(position);
And in call back of onclick use below code
button.getTag()

Set the position of each ViewHolder object as a tag to the buttons and retrieve it using getTag() when they are clicked.
Something like this needs to be done:
viewHolder.btnEdit.setTag(position)
And inside onClick(), retrieve the position as viewHolder.btnEdit.getTag()
For using the viewHolder object inside onClick(), it must be declared final so you can copy the object as final ViewHolder finalHolder = viewHolder and do the above with finalHolder object

Try to set the tag for the buttons at each position in the following way, so that when ever a button is clicked you can get back the position using the tag.
#NonNull
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
// Get the data item for this position
sale = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_sales, parent, false);
//Fetch other views here .....
viewHolder.btnEdit = (ImageButton) convertView.findViewById(R.id.row_sales_btn_edit);
viewHolder.btnRemove = (ImageButton) convertView.findViewById(R.id.row_sales_btn_trash);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
//Setting the position as the tag for both buttons
viewHolder.btnRemove.setTag(position);
viewHolder.btnEdit.setTag(position);
Now in click listener..
viewHolder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Remove the below line
int pos = new Integer(getPosition(sale));
//Use this
int pos = (int)v.getTag();
removeSale(pos);
}
});
Hope, am helpful.

holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (fileDataVo.isPdf()) {
Intent intent = new Intent(context, PdfActivity.class);
intent.putExtra("position", position);
context.startActivity(intent);
} else if (fileDataVo.isExcel()) {
Intent intent = new Intent(context, ExcelFileActivity.class);
intent.putExtra("position", position);
context.startActivity(intent);
}
else if (fileDataVo.isPpt()) {
Intent intent = new Intent(context, PptActivity.class);
intent.putExtra("position", position);
context.startActivity(intent);
}
}

Related

textview not visible in listview when a button is clicked on a particular row

I have an custom listview which contains button and textview. The textview visibility is gone. When the button text is "email" and if I click on button the textview should display below the button. But the last textview is always getting visible.
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
wantedUsers du = wusers.get(i);
final String mcontact = du.mcontact;
if(view==null) {
viewholder = new viewholder();
view = LayoutInflater.from(ws).inflate(R.layout.wantedmoviecustom, null);
viewholder.mcontwcustom = (Button)view.findViewById(R.id.mcontwcustom);
viewholder.mdisplayemail = (TextView) view.findViewById(R.id.mdisplayemail);
view.setTag(viewholder);
} else {
viewholder = (viewholder) view.getTag();
}
viewholder.mdisplayemail.setVisibility(View.GONE);
if(mcontact.contains("#")) {
viewholder.mcontwcustom.setText("Show Email");
viewholder.mdisplayemail.setText(mcontact);
} else {
viewholder.mcontwcustom.setText("Call");
}
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mcontact.contains("#")) {
int p=(Integer)view.getTag();
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
// viewholder.mdisplayemail.setText(mcontact);
}
else
{
Uri call = Uri.parse("tel:" + mcontact);
Intent surf = new Intent(Intent.ACTION_DIAL, call);
ws.startActivity(surf);
}
}
});
viewholder.mcontwcustom.setTag(i);
return view;
}
below is my getview from custom adapter. So how can I make a textview visbile when a button clicked on particular row.
First, you need to create a Global variable
int positionOfButtonClick = -1;
then you need to update your position on button click and need to call notifyDataSetChanged();
like - :
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
positionOfButtonClick = i;
notifyDataSetChanged();
//your other code
});
Then, in getView
you need to check the position and need to VISIBLE your textView like -:
if(i==positionOfButtonClick ){
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
}
Now, your getView should be-:
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
wantedUsers du = wusers.get(i);
final String mcontact = du.mcontact;
if(view==null) {
viewholder = new viewholder();
view = LayoutInflater.from(ws).inflate(R.layout.wantedmoviecustom, null);
viewholder.mcontwcustom = (Button)view.findViewById(R.id.mcontwcustom);
viewholder.mdisplayemail = (TextView) view.findViewById(R.id.mdisplayemail);
if(i==positionOfButtonClick ){
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
}else{
viewholder.mdisplayemail.setVisibility(View.GONE);
}
view.setTag(viewholder);
} else {
viewholder = (viewholder) view.getTag();
}
if(mcontact.contains("#")) {
viewholder.mcontwcustom.setText("Show Email");
viewholder.mdisplayemail.setText(mcontact);
} else {
viewholder.mcontwcustom.setText("Call");
}
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mcontact.contains("#")) {
int p=(Integer)view.getTag();
positionOfButtonClick = i;
notifyDataSetChanged();
}
else
{
Uri call = Uri.parse("tel:" + mcontact);
Intent surf = new Intent(Intent.ACTION_DIAL, call);
ws.startActivity(surf);
}
}
});
viewholder.mcontwcustom.setTag(i);
return view;
}
Change in code as mention below, I think it help you.
viewholder.mcontwcustom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mcontact.contains("#")) {
int p=(Integer)view.getTag();
viewholder.mdisplayemail.setVisibility(View.VISIBLE);
// viewholder.mdisplayemail.setText(mcontact);
}

list view repeating values several times and repeating check box selection every after 6th value

I am using a custom list view base adapter. while passing values to the adapter its repeating values. and in viewholder I am using a checkbox, while selecting that checkbox list auto select the every 6th checkbox after that.
here is my adapter full code.
public class CallLogAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater li;
List<CallLogInfo> callData;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Context context;
static Boolean checkboxstate[];
ArrayList<MultipleSelectedContact> mainDataList;
int i = 0;
public CallLogAdapter(Activity activity, List<CallLogInfo> callData, ArrayList<MultipleSelectedContact> selectedContacts) {
this.activity = activity;
this.callData = callData;
this.mainDataList = selectedContacts;
context = activity;
checkboxstate = new Boolean[callData.size()];
}
// View lookup cache
private static class ViewHolder {
TextView phoneNo, date, addComment, duration;
CheckBox checkBox;
CardView card;
ImageView callTypeImage;
int count;
}
#Override
public int getCount() {
if (callData != null && callData.size() != 0) {
return callData.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return callData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder viewHolder; // view lookup cache stored in tag
if (v == null) {
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.single_card, parent, false);
viewHolder = new ViewHolder();
viewHolder.card = (CardView) v.findViewById(R.id.card_view);
viewHolder.callTypeImage = (ImageView) v.findViewById(R.id.callTypeImage);
viewHolder.phoneNo = (TextView) v.findViewById(R.id.phoneNoText);
viewHolder.date = (TextView) v.findViewById(R.id.dateText);
viewHolder.duration = (TextView) v.findViewById(R.id.callDurationText);
viewHolder.checkBox = (CheckBox) v.findViewById(R.id.checkBox);
viewHolder.addComment = (TextView) v.findViewById(R.id.addCommentText);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) v.getTag();
}
viewHolder.count = position;
final CallLogInfo Info;
Info = callData.get(position);
switch (Info.callType) {
case "Outgoing":
viewHolder.callTypeImage.setImageResource(R.mipmap.up_arrow);
break;
case "Incoming":
viewHolder.callTypeImage.setImageResource(R.mipmap.down_arrow);
break;
case "Missed":
viewHolder.callTypeImage.setImageResource(R.mipmap.miss_arrow);
break;
}
viewHolder.phoneNo.setText(Info.phoneNo);
viewHolder.date.setText(Info.date);
viewHolder.duration.setText(Info.duration);
viewHolder.addComment.setTag(viewHolder.count);
viewHolder.checkBox.setTag(viewHolder.count);
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (((CheckBox) view).isChecked()) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = true;
mainDataList.add(i, new MultipleSelectedContact());
mainDataList.get(i).phoneNoS = Info.phoneNo;
mainDataList.get(i).setIsSelected(viewHolder.checkBox.isSelected());
map.put(((int) viewHolder.checkBox.getTag()), i);
i++;
view.setSelected(true);
} else {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
mainDataList.remove(map.get(((int) viewHolder.checkBox.getTag())));
view.setSelected(false);
}
}
});
viewHolder.addComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_add_comment);
dialog.setTitle("Add Comment Here..");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.messageEditText);
Button dialogButton = (Button) dialog.findViewById(R.id.messageAddButton);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String comment = text.getText().toString();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "CallLogDb", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession session = daoMaster.newSession();
CallCommentsDetailDao callCommentDao = session.getCallCommentsDetailDao();
CallCommentsDetail commentInfo = new CallCommentsDetail();
commentInfo.setCommentId(position);
commentInfo.setComments(comment);
callCommentDao.insertOrReplace(commentInfo);
session.clear();
db.close();
dialog.dismiss();
}
});
dialog.show();
}
});
viewHolder.card.setTag(position);
viewHolder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MessageContentActivity.class);
intent.putExtra("callDetails", Info);
context.startActivity(intent);
}
});
return v;
}
}
Here in the code where I am using ((int) viewHolder.checkBox.getTag()) . I tried using position also. but still its not working..
can anyone please help me to find out where I am going wrong
Set your check box state on getView
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewholder.checkbox.setChecked(checkboxstate[((int)viewHolder.checkBox.getTag())]);
You can use a SparseBooleanArray to save the states of the checkbox instead of setting it as tag and you are not setting the checkbox state in getView() method like
viewholder.checkbox.setChecked(booleanArray.valueAt(position))
then toggle the state on OnClick() something like
booleanArray.put(position,!booleanArray.valueAt(position));
notifyDataSetChanged();
Also listItemClick won't work properly if the list row contains checkboxes or buttons.Use Recyclerview for better customisation and performance.
Sample Implementation of recyclerview

Getting Text from Textview in Listview inflated Layout

I have a listview in which I inflate a layout with multiple textviews and buttons. I understand to get the text from a view that was clicked is ((Textview)view.... However I am trying to get the text from the specific textview that is located in the layout in which the user clicked. I have tried using OnItemClick but when I use this the item must be focused before the any of the buttons functions work. I resorted to and prefer using onClickListeners in the getView method of my custom adapter. So simply put, how do I click a Button and get the text that is in TextView that is located in the appropriate inflated layout list view item, given that since each inflated layout is considered as one list item?
UPDATE
Here are pictures to clarify what i am looking for. Both layouts are members of a listview.
I want to click the button with the date on it and get the text from the textview in the middle of the layout. However when I click the button with the date on it, I can only get the text from the textview in the middle of the layout of the last child. If "My Party" is the first child in the listview and "3303 going away service..." is the second child, when I click the date button the code in my custom adapter returns the text from the last loaded text in the view which will be "3303 going away service". What I am trying to do is when I click the date button on "My party", get the text "My party". Like wise with the second child.
Here is the getView() in my custom adapter.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder = new ViewHolder();
positionHolder = position;
Log.i("Position", "" + position);
if(convertView == null) {
try {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.post_layout, parent, false);
postLayout = convertView;
viewHolder.unameTV = (TextView) postLayout.findViewById(R.id.postUnameTv);
viewHolder.unameTV.setText(viewContent.get(index));
viewHolder.unameTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Starting new intent
Intent in = new Intent(getActivity(),
Profile.class);
// sending pid to next activity
String username =((TextView)view).getText().toString();
in.putExtra("username", username);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
viewHolder.fillSpace = (TextView)postLayout.findViewById(R.id.posthelpSpace);
viewHolder.fillSpace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.unameTV.performClick();
}
});
viewHolder.image = (ImageView) postLayout.findViewById(R.id.postProfPic);
DisplayImageOptions options = initiateDisplayImageOptions();
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.unameTV.performClick();
}
});
ImageLoader imageloader = ImageLoader.getInstance();
initImageLoader(getActivity());
imageloader.displayImage(viewContent.get(index + 1), viewHolder.image, options);
viewHolder.addToCalendarButton = (TextView) postLayout.findViewById(R.id.addToCalendarButton);
viewHolder.addToCalendarButton.setText(viewContent.get(index + 2));
viewHolder.addToCalendarButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.MONTH, 2);
long time = cal.getTime().getTime();
Uri.Builder builder =
CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
builder.appendPath(Long.toString(time));
Intent intent =
new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);
title = testText.getText().toString();
Log.i("Title", "" + title);
intent.putExtra("title", title); // **NOT WORKING**
startActivity(intent);
}
});
viewHolder.eventTitle = (TextView) postLayout.findViewById(R.id.postTitleTV);
viewHolder.eventTitle.setText(viewContent.get(index + 3));
viewHolder.eventTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
title = ((TextView)view).getText().toString();
Log.i("TITLE", "" + title);
}
});
testText = viewHolder.eventTitle;
viewHolder.eventImage = (ImageView) postLayout.findViewById(R.id.eventImage);
imageloader.displayImage(viewContent.get(index + 4), viewHolder.eventImage, options);
viewHolder.likesTV = (TextView) postLayout.findViewById(R.id.likesTV);
viewHolder.likesTV.setText("" + viewContent.get(index + 5));
viewHolder.planToAttendTV = (TextView) postLayout.findViewById(R.id.planToAttendTV);
viewHolder.planToAttendTV.setText(viewContent.get(index + 6));
viewHolder.addressTV = (TextView) postLayout.findViewById(R.id.postLocationTV);
viewHolder.addressTV.setText("" + viewContent.get(index + 7));
index = index + 8;
}
catch (IndexOutOfBoundsException ie)
{
ie.printStackTrace();
}
}
else
{
viewHolder = (ViewHolder) postLayout.getTag();
}
return postLayout;
}
Create a custom baseadapter and set on click listener for text view in the adapter. This will then be set for the specific text view corresponding to the position.
I think you already have custom BaseAdapter created, in the custom BaseAdapter setOnclicklistener of the textview to which you want the click to be registered.
Sample Code Below
public class M_Adapter extends BaseAdapter {
private LayoutInflater inflater = null;
private TextView contact_name;
private Context context;
private List<String> list;
private List<String> temp;
private Button btn;
public M_Adapter(Context context) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
list = new ArrayList<String>();
//add some values in list here
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
final View rowview = inflater.inflate(R.layout.contact_listrow, parent, false);
contact_name = (TextView) rowview.findViewById(R.id.excl_ppl_contact_name);
btn=(Button)rowview.findViewById(R.id.excl_ppl_btn);
contact_name.setText(list.get(temp));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("myapp", "text clicked " + contact_name.getText());
}
});
return rowview;
}
}
I solved this problem with two series of if/else statements. First, in my onBindViewHolder (your getView) I have some global String variables take on the value of the TextView I'm interested in. Second, in the onClick method, I have the ViewHolder tell me the position of the item clicked using the getPosition method. Last, I match the value of the position clicked with the String variables created in the first part and carry on from there.
public void onBindViewHolder(final ViewHolder holder, final int position) {
YelpAPI.businessNumber = position;
YelpAPI.queryAPI(YelpAPI.yelpApi, YelpAPI.yelpApiCli);
Picasso.with(mContext).load(YelpAPI.picture).into(holder.yelpPicture);
holder.textName.setText(YelpAPI.name);
holder.textRating.setText(YelpAPI.rating);
holder.textReviews.setText(YelpAPI.reviews);
holder.textAddressDetails.setText(YelpAPI.fullAddress);
holder.textInfo.setText(YelpAPI.moreInfo);
holder.textID.setText(YelpAPI.businessID);
---------- First...
if(position == 0){
firstBusiness = YelpAPI.businessID; //these three String variables get created above
} else if(position == 1){
secondBusiness = YelpAPI.businessID;
} else if (position == 2) {
thirdBusiness = YelpAPI.businessID;
}
holder.business.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
----------Second...
int specific = holder.getPosition();
----------Last...
String saveMe = "";
if(specific == 0){
saveMe = firstBusiness;
} else if(specific == 1){
saveMe = secondBusiness;
} else if(specific == 2){
saveMe = thirdBusiness;
}
Log.d("Clicked this item: ", String.valueOf(specific));`

Custom ListView in an Alert Dialog with buttons

I have a custom listview that contains two buttons on each line, what I am struggling with is the Listener for these buttons. My Listview is contained within a AlertDialog and this is the code I have
#Override
public void displayUnders(List<UndersLM> ulm) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
ArrayList<UndersLM> undersreturn = new ArrayList<UndersLM>();
final ListView L = new ListView(ctx);
final UndersLM y = new UndersLM();
for (UndersLM aulm : ulm) {
final UndersLM s = new UndersLM();
s.set_id(aulm.get_id());
s.set_cartonid(aulm.get_cartonid());
s.set_sku(aulm.get_sku());
s.set_sentqty(aulm.get_sentqty());
s.set_scannedqty(aulm.get_scannedqty());
undersreturn.add(s);
}
uadaptor = new Unders(ctx, undersreturn);
L.setAdapter(uadaptor);
builder.setView(L);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object rid = parent.getAdapter().getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
L.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object rid = parent.getAdapter().getItem(position);
}
});
AlertDialog d;
d = builder.create();
d.show();
}
As you can see I have tried the ItemClickListerner on the ListView its self, and the itemSelected on the AlertDialog.
What am I missing? Neither one of these ever hits the Object rid = parent.... lines
EDIT - ACTUALLY IGNORE THIS - ITS CRAP!
Ok, worked it out.
You basically have to do this (as far as I can work out) in your Custom Adaptor, so in my case this worked:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.unders, null);
holder = new ViewHolder();
holder.id = (TextView) vi.findViewById(R.id.id);
holder.cartonID = (TextView) vi.findViewById(R.id.cartonID);
holder.Sku = (TextView) vi.findViewById(R.id.Sku);
holder.Sent = (TextView) vi.findViewById(R.id.Sent);
holder.add = (Button) vi.findViewById(R.id.add);
holder.Scanned = (TextView) vi.findViewById(R.id.Scanned);
holder.subtract = (Button) vi.findViewById(R.id.subtract);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Lines.size() < -0) {
holder.id.setText("No Unprocessed Deliveries");
} else {
tempValues = null;
tempValues = (UndersLM) Lines.get(position);
holder.id.setText(String.valueOf(tempValues.get_id()));
holder.cartonID.setText(String.valueOf(tempValues.get_cartonid())+ " | ");
holder.Sku.setText(String.valueOf(tempValues.get_sku()) + " | ");
holder.Sent.setText(String.valueOf(tempValues.get_sentqty()) + " | ");
holder.Scanned.setText(String.valueOf(tempValues.get_scannedqty()));
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new underCorrections(ctx,true,tempValues.get_cartonid(),tempValues.get_sku()).execute();
holder.Scanned.setText(String.valueOf(tempValues.get_scannedqty()+1));
}
});
}
return vi;
}

How to delete a row from a custom ListView when user clicks on a button inside that row

I have created a custom listview and populated it with data, But am finding it hard to delete a row with a button placed inside that same row. Below is the code for the adapter. How can I delete this row. Any ideas ??
public Pursue_results_listview_adapter(Context c, String[] ClientName,
String[] clientId) {
super(c, R.layout.pursuing_list_row, R.id.client, ClientName);
this.context = c;
this.clientIdArray = clientId;
this.ClientNameArray = ClientName;
}
class viewHolder {
TextView client;
ImageView deleteclient;
public viewHolder(View v) {
deleteclient = (ImageView) v.findViewById(R.id.deleteclient);
client = (TextView) v.findViewById(R.id.client);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
viewHolder holder = null;
if (row == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflator.inflate(R.layout.pursuing_list_row, parent, false);
holder = new viewHolder(row);
row.setTag(holder);
} else {
holder = (viewHolder) row.getTag();
}
final String clientid = cleintIdArray[position];
holder.client.setText(ClientNameArray[position]);
holder.deleteclient.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//delete client
notifyDataSetChanged();
}
});
return row;
}
try this
holder.deleteclient.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
int index = Integer.parseInt(v.getTag().toString())
data.remove(index); //where 'data' is your list
notifyDataSetChanged();
}
});
Try to set the position in the tag like setTag(position) and in onClick remove the position like
Integer i= (Integer) view.getTag();
list.remove(i.intValue());
Try something like this, Also is there any reason you aren't using some sort of collection to hold your data? It would make the it much simpler.
Firstly making clientIdArray and clientNameArray into Arraylists
Arraylist<String> clientIdArray;
Arraylist<String> clientNameArray;
then change this
this.clientIdArray = clientId;
this.ClientNameArray = ClientName;
to
this.clientIdArray = new Arraylist<String>(Arrays.asList(clientId));
this.ClientNameArray = new Arraylist<String>(Arrays.asList(ClientName));
And then your code becomes this
//Store the index that is being deleted in this views tag
holder.deleteclient.setTag(position)
holder.deleteclient.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
//get the index back
int index = (Integer)v.getTag();
//Removal code goes here, if you don't want to make your arrays into arraylists
//you will need to write your own removal code
clientIdArray.remove(index);
ClientNameArray.remove(index);
notifyDataSetChanged();
}
});

Categories

Resources