I have a ListView,I am having a custom ListItem designed for it having some TextView's and an ImageView. I want to change that particular image when clicked . I have tried but when i click on that image from ListView, the below listItem's image is changing.
For example if i click on 0th position image then image is changing of 1st position ListIem and when i scroll up and down the List,it changes randomly.
I dont know what is happening with it,I have used notifydatasetChanged on my adapter,But its not working,My code is as below.
Please help me,Thank you,
Code
private class RssAdapter extends ArrayAdapter<RSSFeed_SelectedHotelResult> {
private List<RSSFeed_SelectedHotelResult> rssFeedLst;
int selectedPosition;
public RssAdapter(Context context, int textViewResourceId,
List<RSSFeed_SelectedHotelResult> rssFeedLst) {
super(context, textViewResourceId, rssFeedLst);
this.rssFeedLst = rssFeedLst;
Boolean addtoShotlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = View.inflate(HotelListActivity.this, R.layout.list_row,
null);
rssHolder = new RssHolder();
rssHolder.iv_add = (ImageView) view.findViewById(R.id.iv_add);
rssHolder.rssTitleView = (TextView) view
.findViewById(R.id.title);
rssHolder.tv_offer = (TextView) view.findViewById(R.id.tv_ofr);
rssHolder.rssImagHotel = (ImageView) view
.findViewById(R.id.hotelImage);
rssHolder.rssImageHotelRate = (ImageView) view
.findViewById(R.id.rateHotel2);
rssHolder.rssHotelPrice = (TextView) view
.findViewById(R.id.textHotelRate);
rssHolder.rssHotelAddress = (TextView) view
.findViewById(R.id.textHotelDesc);
// rssHolder.adres = (TextView) view.findViewById(R.id.adres);
// rssHolder.rssHotelRating = (TextView)
// view.findViewById(R.id.textHotelRating);
rssHolder.rating_hotel = (RatingBar) view
.findViewById(R.id.rateHotelImage);
rssHolder.tv_currcode = (TextView) view
.findViewById(R.id.tv_currcode);
view.setTag(rssHolder);
} else {
rssHolder = (RssHolder) view.getTag();
}
final RSSFeed_SelectedHotelResult rssFeed = rssFeedLst
.get(position);
rssHolder.rssTitleView.setText(rssFeed.getName());
imageLoader.DisplayImage(rssFeed.getHotel_image(),
rssHolder.rssImagHotel);
imageLoader.DisplayImage_rating(rssFeed.getHote_rate_image(),
rssHolder.rssImageHotelRate);
rssHolder.rssHotelPrice.setText(rssFeed.getHotel_price());
rssHolder.rssHotelAddress.setText(rssFeed.getHotel_desc());
rssHolder.rating_hotel.setRating(Float.valueOf(rssFeed
.getHotel_rate()));
rssHolder.tv_currcode.setText(Consts.currencyCode);
if (rssFeed.getoffer() != null) {
rssHolder.tv_offer.setText("**" + rssFeed.getoffer() + "**");
} else {
rssHolder.tv_offer.setText("");
}
rssHolder.iv_add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
selectedPosition = position;
try {
if (position == selectedPosition) {
rssHolder.iv_add
.setBackgroundResource(R.drawable.fill);
} else {
rssHolder.iv_add
.setBackgroundResource(R.drawable.plus12);
}
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("::::::::::::My data in side hotel List activity:::::::::;"
+ position
+ ""
+ rssFeed.getName()
+ "\n"
+ rssFeed.getHotel_price());
/*
* RSSFeed_SelectedHotelResult rssFeed1 = rssFeedLst
* .get(position);
*/
}
});
return view;
}
}
For notify data-set changed your calling the wrong method the correct method is adapter.notifyDataSetChanged()
1.) Write this code inside your custom adapter getView :
if (position == selectedPosition) {
imageview.setBackgroundResource(R.drawable.image1);
} else {
imageview.setBackgroundResource(R.drawable.normal);
}
2.) Make a method in custom adapter :
public void setSelected(int position) {
selectedPosition = position;
}
//where selectPosition is private int selectedPosition = -1;
3.) Call this method from activity listitem click like :
((Category_Adapter) adapter).setSelected(position);
listview.invalidate();
Make sure your listview set to single choice mode.
private class RssAdapter extends ArrayAdapter<RSSFeed_SelectedHotelResult> {
private List<RSSFeed_SelectedHotelResult> rssFeedLst;
private int selectedPosition =-1;// initalize position
public RssAdapter(Context context, int textViewResourceId,
List<RSSFeed_SelectedHotelResult> rssFeedLst) {
super(context, textViewResourceId, rssFeedLst);
this.rssFeedLst = rssFeedLst;
Boolean addtoShotlist;
}
//make this method
public void setSelected(int position) {
selectedPosition = position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
if (convertView == null) {
view = View.inflate(HotelListActivity.this, R.layout.list_row,
null);
rssHolder = new RssHolder();
rssHolder.iv_add = (ImageView) view.findViewById(R.id.iv_add);
rssHolder.rssTitleView = (TextView) view
.findViewById(R.id.title);
rssHolder.tv_offer = (TextView) view.findViewById(R.id.tv_ofr);
rssHolder.rssImagHotel = (ImageView) view
.findViewById(R.id.hotelImage);
rssHolder.rssImageHotelRate = (ImageView) view
.findViewById(R.id.rateHotel2);
rssHolder.rssHotelPrice = (TextView) view
.findViewById(R.id.textHotelRate);
rssHolder.rssHotelAddress = (TextView) view
.findViewById(R.id.textHotelDesc);
// rssHolder.adres = (TextView) view.findViewById(R.id.adres);
// rssHolder.rssHotelRating = (TextView)
// view.findViewById(R.id.textHotelRating);
rssHolder.rating_hotel = (RatingBar) view
.findViewById(R.id.rateHotelImage);
rssHolder.tv_currcode = (TextView) view
.findViewById(R.id.tv_currcode);
view.setTag(rssHolder);
} else {
rssHolder = (RssHolder) view.getTag();
}
final RSSFeed_SelectedHotelResult rssFeed = rssFeedLst
.get(position);
rssHolder.rssTitleView.setText(rssFeed.getName());
imageLoader.DisplayImage(rssFeed.getHotel_image(),
rssHolder.rssImagHotel);
imageLoader.DisplayImage_rating(rssFeed.getHote_rate_image(),
rssHolder.rssImageHotelRate);
rssHolder.rssHotelPrice.setText(rssFeed.getHotel_price());
rssHolder.rssHotelAddress.setText(rssFeed.getHotel_desc());
rssHolder.rating_hotel.setRating(Float.valueOf(rssFeed
.getHotel_rate()));
rssHolder.tv_currcode.setText(Consts.currencyCode);
if (rssFeed.getoffer() != null) {
rssHolder.tv_offer.setText("**" + rssFeed.getoffer() + "**");
} else {
rssHolder.tv_offer.setText("");
}
rssHolder.iv_add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//remove selectposition = position
try {
if (position == selectedPosition) {
rssHolder.iv_add
.setBackgroundResource(R.drawable.fill);
} else {
rssHolder.iv_add
.setBackgroundResource(R.drawable.plus12);
}
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("::::::::::::My data in side hotel List activity:::::::::;"
+ position
+ ""
+ rssFeed.getName()
+ "\n"
+ rssFeed.getHotel_price());
/*
* RSSFeed_SelectedHotelResult rssFeed1 = rssFeedLst
* .get(position);
*/
}
});
return view;
}
}
Finally call adapter selected method from activity listitem click and set position.
Related
I used GridView to display images of types of batteries. When user clicks any image, the features of that particular battery will get print on next page. The images and features are fetching from the server. The problem is the first battery image is displaying when I opened the GridView, but the other battery images are displaying in that GridView only after I scroll the screen two to three times. But I want to display all the images once I opened the GridView.
private void getDatasFromIntent() {
alHM = new ArrayList<>();
Intent intent = getIntent();
String typeResp = intent.getStringExtra("IMG_S");
try {
JSONObject jsonObject = new JSONObject(typeResp);
JSONArray jsonArray = jsonObject.getJSONArray("process");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hm = new HashMap<>();
JSONObject bat_json = jsonArray.getJSONObject(i);
String battery_featues_id = bat_json.getString("battery_featues_id");
String battery = bat_json.getString("battery_type");
String battery_image = bat_json.getString("battery_image");
battery_image = battery_image.replace("\\", "");
hm.put("battery_featues_id", battery_featues_id);
hm.put("battery_type", battery);
hm.put("battery_image", battery_image);
alHM.add(hm);
}
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this, alHM);
// Set custom adapter to gridview
GridView gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(SampleBatteryList.this, "a: " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GridviewAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> list;
private final SampleBatteryList activity;
public GridviewAdapter(SampleBatteryList sampleBatteryList,
ArrayList<HashMap<String, String>> alHM) {
this.activity = sampleBatteryList;
this.list = alHM;
Log.d("VOLLY", "ADP :" + alHM);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class ViewHolder {
public ImageView imgViewFlag;
public TextView txtViewTitle;
public Button button;
ViewHolder view;
}
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
}
here you are using view holder class but after initialization part and assign value part are in if and else so value not showing.
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
change to
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
}else{
view = (ViewHolder) contentView.getTag();
}
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
return contentView;
}
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 am able to access the individual row of listview.
But listview.setOnItemClickListener() method is not working.
Actually on listview row there is button I can access that also I'm able to set ClickListener on it.It's Working.
But the problem is listview.setOnItemClickListener() method is not responding.Is it possible
to have that both functionality.Thanks in Advance,Sorry for My english.
This is my getView
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.i("Position", "" + position);
view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new AttractionViewHolder();
holder.tvName = (TextView) view.findViewById(R.id.attName);
holder.add = (Button) view.findViewById(R.id.attAdd);
holder.tvdetails = (TextView) view.findViewById(R.id.attDetails);
holder.attImage = (ImageView) view.findViewById(R.id.attImage);
holder.attPbar = (ProgressBar) view.findViewById(R.id.attProgress);
holder.ratingBar = (RatingBar) view.findViewById(R.id.attRating);
view.setTag(holder);
} else {
holder = (AttractionViewHolder) view.getTag();
}
placeObject = placeList.get(position);
name = placeObject.getName();
holder.tvName.setText(name);
holder.attPbar.setVisibility(View.INVISIBLE);
holder.attImage.setImageResource(R.drawable.img1);
holder.ratingBar.setRating(Float.parseFloat(Integer
.toString(placeObject.getStar())));
holder.tvdetails.setTag(position);
holder.add.setBackgroundResource(R.drawable.add);
holder.add.setTag(position);
holder.add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id[] = new String[placeList.size()];
String name[] = new String[placeList.size()];
Object o = v.getTag();
int pos = Integer.parseInt(o.toString());
Log.i("Pos", "" + pos);
if (position == pos) {
placeObject = placeList.get(position);
if (id.length > i) {
id[i] = placeObject.getId();
name[i] = placeObject.getName();
i++;
}
}
}
});
holder.tvdetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Object o = v.getTag();
int pos = Integer.parseInt(o.toString());
if (pos == position) {
Log.i("Click","You Clicked");
}
}
});
return view;
}
public class AttractionViewHolder {
public TextView tvName, tvdetails;
private ImageView attImage;
private ProgressBar attPbar;
private Button add;
RatingBar ratingBar;
}
for each Button add this to layout:
android:focusable="false"
and then in getView find each Button and then assign it the appropriate click listener.
android:focusable="false" for Button.
In this case you ListView will fire onItemClick action to listener, and the Button will also work when it clicked.
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.