I have created a listview that has an image and a button - I am using ArrayAdapter to view the items in the listview.
When I click on the button I would like to get the details of the item clicked.
So I tried the following:
pd = productList.get(position);
Where productList is ArrayList<ProductDetails> productList;
getproductdetailsbutton is a button in productListadapter extends ArrayAdapter<ProductDetails>
holder.getproductdetailsbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String productID = pd.getProductID();
String productName = pd. getProductName();
Log.d("Value", " Product Details " + productID + " " + productName);
}
});
When I click the button from the first item, I get details of the last item displayed on the screen in the log.
How do I get the details of clicked item for that position?
Thanks!
UPDATE: getVIEW Code:
#Override
public View getView(final int position, View convertView, final ViewGroup parent)
{
Typeface tf = Typeface.createFromAsset(contextValue.getAssets(), fontPath);
Typeface tf2 = Typeface.createFromAsset(contextValue.getAssets(), fontPath2);
ViewHolder holder = null;
if (convertView == null)
{
convertView = vi.inflate(R.layout.product_details_items, null);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(R.id.productimage);
holder.productgetdetails = (Button) convertView.findViewById(R.id.productgetdetails);
holder.productgetdetails.setTag(position);
holder.productgetdetails.setTypeface(tf2);
convertView.setTag(holder);
ProductDetails pd = productList.get(position);
if (pinexist.equalsIgnoreCase(contextValue.getString(R.string.pinexistvalue)))
{
Log.d("Value"," - ID " + pd.getProductID());
if (logdb.checkproductDetailsExists(pd.getProductID()) == 0)
{
holder.productgetdetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.e("Value", " = FINAL" + productList.get(position).getProductID());
}
});
}
else
{
holder.productgetdetails.setText(contextValue.getString(R.string.nodata));
}
}
else
{
//DO NOTHING
}
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ProductDetails pd = productList.get(position);
Glide.with(getContext().getApplicationContext())
.load(pd.getProduct_image())
.placeholder(R.drawable.placeholder)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.image);
return convertView;
}
I guess(actually I'm confident), you must be declaring pd as global variable, which gets updated by last item displayed, try to move pd into getView() and mark it as final so you can use it inside onclick as in
public void getView(){
final ProductDetails pd = productList.get(position);
// your code for click
}
When inflating your layout to view in Adapter
you can set the OnClickListener on the button
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.list_layout, null,true);
final Product pd = pdList.get(position);
//....
Button btn= (Button) = rowView.findViewById(R.id.getproductdetailsbutton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String productID = pd.getProductID();
String productName = pd.getProductName();
Log.d("Value", " Product Details " + productID + " " + productName);
}
});
//..
return rowView;
};
Or you can handle ListView OnItemClickListener
Related
enter image description hereI want that if user clicks + and - button then action performed to that particular list item in listview. In my program when I clicked first item's button then value increment and decrement also but when another items button clicked that time it consider previous items value and incerement and decrement action performed on that value .I want that each item perform their seperately. I don't know how to implement this.
Here my code:
public static class ViewHolder {
TextView tv_qty;
}
public class ProductAdapter extends ArrayAdapter<Product> {
ImageLoader imageLoader;
public ProductAdapter(Context context, int resource) {
super(context, resource);
imageLoader = new ImageLoader(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Product product = getItem(position);
// Product product=ge
View view;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.product_row, null);
} else {
view = convertView;
}
final ViewHolder viewHolder = new ViewHolder();
tv_row_product_name = (TextView) view.findViewById(R.id.pname);
tv_row_product_rate = (TextView) view.findViewById(R.id.price);
tv_row_product_qty = (TextView) view.findViewById(R.id.productqty);
viewHolder. tv_qty = (TextView) view.findViewById(R.id.userqty);
tv_value = (TextView) findViewById(R.id.textView_value);
tv_totalprice = (TextView) findViewById(R.id.textview_totalprice);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
Log.d(Config.tag, "url : " + "uploads/product/" + product.image1);
Picasso.with(ListViewProduct.this)
.load("http://www.sureshkirana.com/uploads/product/" + product.image1)
.into(imageView);
imgbtnp = (ImageButton) view.findViewById(R.id.imageButton2);
imgbtnm = (ImageButton) view.findViewById(R.id.imageButton);
imgbtnp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count++;
viewHolder. tv_qty.setText(String.valueOf(count));
notifyDataSetChanged();
}
});
imgbtnm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (count > 0)
count--;
viewHolder.tv_qty.setText(String.valueOf(count));
notifyDataSetChanged();
}
});
view.setTag(viewHolder);
tv_row_product_name[enter image description here][1].setText(product.productTitle);
tv_row_product_rate.setText("Rs. " + product.productPrice + "/-");
tv_row_product_qty.setText(product.quantity + "kg");
tv_totalprice.setText("Rs." + product.product_amount);
return view;
}
}
}
You cannot use a single variable for this purpose. Set the count as tag to your list item viewHolder.tv_qty.setTag(count);
and retrieve the value like viewHolder.tv_qty.getTag();.
on clicking on the + or - sign get the position of the clicked item in getView and get the product object at that position and modify with the new values and again put the modified object inside same list at same position and call notifyDatasetChanged() . Hope it helps.
Using Interface you can solve this problem. You need to update your object and then refresh you list adapter using notifyDataSetChanged().
Custom Adapter
public interface QuantityClickListener {
void onIncrementClickListner(int position);
void onDecrementClickListner(int position);
}
/*
* (non-Javadoc)
*
* #see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ListViewWrapper wrapper = null;
LayoutInflater inflater = LayoutInflater.from(mContext);
if (null == convertView) {
convertView = inflater.inflate(R.layout.custom_list_item, null);
wrapper = new ListViewWrapper(convertView);
convertView.setTag(wrapper);
} else {
wrapper = (ListViewWrapper) convertView.getTag();
}
// Schedule schedule = objects.get(position);
Products product = mProducts.get(position);
if (null != product) {
wrapper.getTxtQuantity().setText("" + product.quantity);
wrapper.getNegativeBtn().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
quantityClickListener.onDecrementClickListner(position);
}
});
wrapper.getPositiveBtn().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
quantityClickListener.onIncrementClickListner(position);
}
});
}
return convertView;
}
Activity
/**
* Initialize UI elements
*/
private void initialize() {
listView = (ListView) findViewById(R.id.listview);
dummyData();
adapters = new CustomAdapters(this, 0, products);
adapters.setQuantityClickListener(quantityClickListener);
listView.setAdapter(adapters);
}
private QuantityClickListener quantityClickListener = new QuantityClickListener() {
#Override
public void onIncrementClickListner(int position) {
if (null != products && products.size() > 0) {
Products product = products.get(position);
product.quantity++;
product.totalPrice = product.quantity * product.price;
adapters.notifyDataSetChanged();
}
}
#Override
public void onDecrementClickListner(int position) {
if (null != products && products.size() > 0) {
Products product = products.get(position);
if (product.quantity > 0) {
product.quantity--;
product.totalPrice = product.quantity * product.price;
adapters.notifyDataSetChanged();
}
}
}
};
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));`
I am working on custom adapter. I created separate class for it which extends BaseAdapter. I am having two images - (minus) and + (plus) which will decrease or increase quantity of product in list view.
List item looks like
[ - Product qty + ]
Now I already implemented listener for - (minus) image and it is working. But listener for + (plus) image is not working. I printed qty on the console it is incrementing but not getting updated in listview.
Here is the code
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row_sold_item, null);
TextView txtListItem = (TextView) vi.findViewById(R.id.txtListItem);
txtQuantity = (TextView) vi.findViewById(R.id.txtQuantity);
ImageView imgCancel = (ImageView) vi.findViewById(R.id.imgCancel);
ImageView imgPlus = (ImageView) vi.findViewById(R.id.imgPlus);
HashMap<String, String> mapData = new HashMap<String, String>();
mapData = data.get(position);
txtListItem.setText(mapData.get("product"));
txtQuantity.setText(mapData.get("qty"));
imgCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doButtonOneClickActions(position);
}
});
imgPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qtyClickAction(position);
}
});
return vi;
}
private void qtyClickAction(int rowNumber) {
System.out.println(rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
System.out.println("before : " + qty);
qty++;
txtQuantity.setText("" + qty);
System.out.println("after : " + qty);
notifyDataSetChanged();
}
private void doButtonOneClickActions(int rowNumber) {
// Do the actions for Button one in row rowNumber (starts at zero)
System.out.println("rowNumber : " + rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
if (qty == 1) {
data.remove(rowNumber);
} else {
txtQuantity.setText("" + --qty);
}
notifyDataSetChanged();
}
One more thing, if I delete item in list, it is getting deleted. But how can I get notification for deleted item in my main class. Consider I selected 3 items, now I removed any one item by clicking - (minus). The item is getting deleted from list - the code is in adapter class
notifyDataSetChanged();
But how can I update total amount which is getting calculated in main class
try this it may help you,
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row_sold_item, null);
TextView txtListItem = (TextView) vi.findViewById(R.id.txtListItem);
TextView txtQuantity = (TextView) vi.findViewById(R.id.txtQuantity);
ImageView imgCancel = (ImageView) vi.findViewById(R.id.imgCancel);
ImageView imgPlus = (ImageView) vi.findViewById(R.id.imgPlus);
HashMap<String, String> mapData = new HashMap<String, String>();
mapData = data.get(position);
txtListItem.setText(mapData.get("product"));
txtQuantity.setText(mapData.get("qty"));
imgCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doButtonOneClickActions(txtQuantity,position);
}
});
imgPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qtyClickAction(txtQuantity,position);
}
});
return vi;
}
private void qtyClickAction(TextView txtQuantity,int rowNumber) {
System.out.println(rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
System.out.println("before : " + qty);
qty++;
txtQuantity.setText("" + qty);
System.out.println("after : " + qty);
}
private void doButtonOneClickActions(TextView txtQuantity,int rowNumber) {
// Do the actions for Button one in row rowNumber (starts at zero)
System.out.println("rowNumber : " + rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
if (qty == 1) {
data.remove(rowNumber);
notifyDataSetChanged();
} else {
txtQuantity.setText("" + --qty);
}
}
try this:
private void qtyClickAction(TextView txtQuantity,int rowNumber) {
System.out.println(rowNumber);
int qty = Integer.parseInt(txtQuantity.getText().toString().trim());
System.out.println("before : " + qty);
qty++;
data.get(rowNumber).set("qty")=qty;
//txtQuantity.setText("" + qty); not needed anymore
System.out.println("after : " + qty);
notifyDataSetChanged();
}
indeed you have not updated the data model so notifyDataSetChanged(); dose not take effect.
In order to send back updated data:
imgCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doButtonOneClickActions(position);
// update totalAmount
txtAmountAdapter.setText(Integer.valueOf(totalAmount).toString()));
}
});
imgPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qtyClickAction(position);
// update totalQty
txtAmountAdapter.setText(Integer.valueOf(totalAmount).toString()));
}
});
and pass txtAmount to the constructor of your adapter and store it as txtAmountAdapter. now every update in total amount update txtAmount in main.
I am using a listview in my Android program.
I have row. 1) i have custom row in button and i want to when click button then open the alert box and this row clicked then open the new activity but Only one button clicked not row clicked . how to possible in this case. my code in below.
Thank you.
public class AlMessagesAdapter extends ArrayAdapter<DtoAllMessages> {
private LayoutInflater inflator;
private ArrayList<DtoAllMessages> userlist;
public AlMessagesAdapter(Activity context, ArrayList<DtoAllMessages> list) {
super(context, R.layout.custom_list, list);
this.userlist = list;
inflator = context.getLayoutInflater();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
convertView.setTag(holder);
convertView.setTag(R.id.tvName, holder.title);
convertView.setTag(R.id.tvDate, holder.date_cr);
convertView.setTag(R.id.ivIcon,holder.img);
convertView.setTag(R.id.tokenBtn,holder.tokenBtn);
} else {
holder = (ViewHolder) convertView.getTag();
}
String token = userlist.get(position).getToken();
Log.v("MessageList", "token:" + token);
token = token.substring(0,token.length()-3);
holder.title.setText(userlist.get(position).getName()+"("+token+")");
String type_data = userlist.get(position).getType().toString();
if((type_data.equals("text")) || (type_data.equals("photo")))
{
Log.v("log", " if text photo ");
holder.date_cr.setText(userlist.get(position).getType()+":Received "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.VISIBLE);
list.setItemsCanFocus(true);
}
else if(type_data.equals("out"))
{
Log.v("log", " else out ");
holder.date_cr.setText(userlist.get(position).getType()+":Sent "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.GONE);
}
if(type_data.equals("text"))
{
Log.v("log", " if text ");
holder.img.setBackgroundResource(R.drawable.chatmessage);
}
else if(type_data.equals("photo"))
{
Log.v("log", " ese if photo ");
holder.img.setBackgroundResource(R.drawable.photomessage);
}
else if(type_data.equals("out"))
{
Log.v("log", " ese if out ");
holder.img.setBackgroundResource(R.drawable.outmessafe);
}
if(position%2==0)
{
convertView.setBackgroundResource(R.drawable.whitebackground);
}
else
{
convertView.setBackgroundResource(R.drawable.greybackground);
}
holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
}
});
return convertView;
}
class ViewHolder {
protected ImageView img;
protected TextView date_cr;
protected TextView title;
protected Button tokenBtn;
}
}
and list click event in below::
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
msg = userLIstArray.get(position).getMessage();
token = userLIstArray.get(position).getToken();
type = userLIstArray.get(position).getType();
int msgId = userLIstArray.get(position).getMessageid();
token = token.substring(0,token.length()-3);
int token_value = Integer.parseInt(token) * 1000;
if(type.equals("text"))
{
Log.v("log", " if in text to Display " + msg + " token "+token);
Intent i = new Intent(MessagesList.this,DisplayPopupActivity.class);
i.putExtra("msg", msg);
i.putExtra("token", token);
i.putExtra("msgid", msgId);
startActivity(i);
}
else if(type.equals("photo"))
{
Log.v("log", " else in IMage to Display " + msg + " token "+token);
Log.v("log","token "+token+" type "+type + " position "+position + "msgId "+ msgId);
Intent i = new Intent(MessagesList.this,DisplayImageActivity.class);
i.putExtra("imgData", msg);
i.putExtra("token", token);
i.putExtra("msgid", msgId);
startActivity(i);
//Log.v("log"," Message" +message);
//Toast.makeText(AllMessageActivity.this, "Message "+message, Toast.LENGTH_LONG).show();
}
return false;
}
});
}
Try this,
Instead of button use TextView. and the write onclickListerner to TextView. i had face same issue in ListView Button click using textview now its working fine. just try it.
You can add the row click event using:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
//go to new activity
});
And the button event, as you are doing..
holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
//show alert
}
});
call your clickevent inside if condition
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
holder.tokenBtn.setOnClickListener(click);
}
create clicklistner outside.
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// do your stuff here
}
};
In your Adapter class set an OnclickListner
private LayoutInflater inflator;
private ArrayList<DtoAllMessages> userlist;
private Context context; //added
public AlMessagesAdapter(Activity context, ArrayList<DtoAllMessages> list) {
super(context, R.layout.custom_list, list);
this.context=context; //added
this.userlist = list;
inflator = context.getLayoutInflater();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
holder.tokenBtn.setOnClickListener((OnClickListener)context); //added portion
convertView.setTag(holder);
convertView.setTag(R.id.tvName, holder.title);
convertView.setTag(R.id.tvDate, holder.date_cr);
convertView.setTag(R.id.ivIcon,holder.img);
convertView.setTag(R.id.tokenBtn,holder.tokenBtn);
} else {
holder = (ViewHolder) convertView.getTag();
}
String token = userlist.get(position).getToken();
Log.v("MessageList", "token:" + token);
token = token.substring(0,token.length()-3);
holder.title.setText(userlist.get(position).getName()+"("+token+")");
String type_data = userlist.get(position).getType().toString();
if((type_data.equals("text")) || (type_data.equals("photo")))
{
Log.v("log", " if text photo ");
holder.date_cr.setText(userlist.get(position).getType()+":Received "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.VISIBLE);
list.setItemsCanFocus(true);
}
else if(type_data.equals("out"))
{
Log.v("log", " else out ");
holder.date_cr.setText(userlist.get(position).getType()+":Sent "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.GONE);
}
if(type_data.equals("text"))
{
Log.v("log", " if text ");
holder.img.setBackgroundResource(R.drawable.chatmessage);
}
else if(type_data.equals("photo"))
{
Log.v("log", " ese if photo ");
holder.img.setBackgroundResource(R.drawable.photomessage);
}
else if(type_data.equals("out"))
{
Log.v("log", " ese if out ");
holder.img.setBackgroundResource(R.drawable.outmessafe);
}
if(position%2==0)
{
convertView.setBackgroundResource(R.drawable.whitebackground);
}
else
{
convertView.setBackgroundResource(R.drawable.greybackground);
}
/*holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
}
});*/
return convertView;
}
class ViewHolder {
protected ImageView img;
protected TextView date_cr;
protected TextView title;
protected Button tokenBtn;
}
}
And into your Main class
public Main extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.casual_layout);
Button tokenBtn=(Button)findViewById(R.id.tokenBtn);
tokenBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.tokenBtn:
//Write a code here to execute alertdialog
Log.d("ALERT HERE","ALERT HERE");
break;
}
}
If you want to use a Button instead of a TextView set
android:focusable="false"
to your Button
I have a multicolumn List view like the one shown in the image, i used custom adapters to populate this custom list.so the question is how to get data on click of submit button means when i click submit button i should get data like name, price and quantity of only checked checkbox....Thanx in advance.
In my Main xml i have a listview and in mainlist xml i have txtname, txtprice, edittext and checkbox and use efficient adapter.
i'm able to view data in list view, bt the problem is i m unable to save data on click of submit button... so plz help me out, with a sample code, bcz m new to android..
the following is my code..
public class Menu extends Activity {
ListView list;
Cursor cursorMenu;
Button btnPlaceOrder;
Button btnShowOrders;
String Descstr="";
String strtotal="";
List<String[]> lstSelectedItems = null;
DBAdapter db = new DBAdapter(this);
private String[] strName;
private String[] strPrice;
private String[] strDescription;
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
try {
return strName.length;
} catch (Exception e) {
//Toast.makeText(Menu.this, "No Data !", Toast.LENGTH_LONG).show();
return 0;
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menulist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.txtItemName);
holder.text2 = (TextView) convertView
.findViewById(R.id.txtPrice);
holder.text3 = (TextView) convertView
.findViewById(R.id.txtDescription);
holder.etext3 = (EditText) convertView
.findViewById(R.id.txtQty);
holder.chk = (CheckBox) convertView
.findViewById(R.id.chkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(strName[position]);
holder.text2.setText(strPrice[position]);
holder.text3.setText(strDescription[position]);
return convertView;
}
class ViewHolder {
TextView text;
TextView text2;
TextView text3;
EditText etext3;
CheckBox chk;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
btnPlaceOrder = (Button) findViewById(R.id.btnPlaceOrder);
btnPlaceOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*db.open();
cursorMenu = db.menu_getAllTitles();
int rowcount = cursorMenu.getCount();
System.out.println("---- +++++ " + rowcount);
System.out.println("---- column +++++ " + cursorMenu.getColumnCount());
int index = 0;
if (rowcount > 0) {
strName = new String[rowcount];
strPrice = new String[rowcount];
strDescription = new String[rowcount];
if (cursorMenu.moveToFirst()) {
do {
strName[index] = cursorMenu.getString(1);
strDescription[index] = cursorMenu.getString(2);
strPrice[index] = cursorMenu.getString(3);
Log.v(TAG, "Name-- " + strName[index] + "Price-- "
+ strPrice[index]);
index++;
} while (cursorMenu.moveToNext());
}
cursorMenu.close();
} else {
Toast.makeText(this, "No Data found", Toast.LENGTH_LONG).show();
}*/
list = (ListView) findViewById(R.id.lstMenu);
list.setAdapter(new EfficientAdapter(this));
System.out.println("--List Child count-----"+list.getChildCount());
System.out.println("--List count-----"+list.getCount());
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(),
"You clciked " + strName[arg2] + "\t" + strPrice[arg2],
Toast.LENGTH_LONG).show();
}
});
}
}
http://www.vogella.de/articles/AndroidListView/article.html go through this example you can get every thing regards listview.