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.
Related
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
I have an issue while loading data in adapter view of recycle view.
I have two Fragment in activity and 2nd Fragment have 3 recycle views. But the problem is that I have a checkbox in raw view holder, I checked some one of that. when i scroll up /down then that data of recycleview data rearrange as default and all check boxes are again false.
I used set recycle(false) in on bind method but still not working.
public class VenueOrderPriceAdapter extends
RecyclerView.Adapter<VenueOrderPriceAdapter.DataViewHolder> {
static Context mContext;
public static double final_total;
public static String selected_hr,selected_min;
static private List<VenueOrderPriceModel> stList;
static private String str_id, str_charges, str_is_flat_charges, str_is_per_person_charges;
/*str_hour_extension_charges, str_extra_person_charges=null, str_is_group_size, str_group_size_from,
str_group_size_to*/;
private static boolean isPkgAdded;
public VenueOrderPriceAdapter(Context mContext, List<VenueOrderPriceModel> students) {
this.mContext = mContext;
this.stList = students;
}
// Create new views
#Override
public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_venueorder_price, parent,false);
Log.e("on create called---","dsdf--111");
// create ViewHolder
DataViewHolder viewHolder = new DataViewHolder(itemLayoutView);
final_total=0;
return viewHolder;
}
#Override
public void onBindViewHolder(final DataViewHolder viewHolder, final int positiona) {
Log.e("on bind called---","dsdf"+positiona);
viewHolder.setIsRecyclable(false);
}
// Return the size arraylist
#Override
public int getItemCount() {
return stList.size();
}
public static class DataViewHolder extends RecyclerView.ViewHolder {
public TextView tvName,tv_details,tv_duration ,tv_guestCount,tv_price,tv_extra_charge,tv_addtocart,tv_pkg_rate;
CheckBox cb_selectedprice;
private LinearLayout ll_extra,ll_extra_charge;
Spinner sp_hh,sp_mm,sp_qty;
ImageView img_clock,img_guest,img_remove;
public DataViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvName = (TextView) itemLayoutView.findViewById(R.id.tvName);
tv_details = (TextView) itemLayoutView.findViewById(R.id.tv_details);
tv_duration = (TextView) itemLayoutView.findViewById(R.id.tv_duration);
tv_guestCount = (TextView) itemLayoutView.findViewById(R.id.tv_guestCount);
tv_price = (TextView) itemLayoutView.findViewById(R.id.tv_price);
tv_extra_charge = (TextView)itemLayoutView.findViewById(R.id.tv_extra_charge);
tv_pkg_rate = (TextView)itemLayoutView.findViewById(R.id.tv_pkg_rate);
img_clock = (ImageView) itemLayoutView.findViewById(R.id.img_clock);
img_guest = (ImageView) itemLayoutView.findViewById(R.id.img_guest);
img_remove = (ImageView) itemLayoutView.findViewById(R.id.img_remove);
sp_hh = (Spinner)itemView.findViewById(R.id.sp_hh);
sp_mm = (Spinner)itemView.findViewById(R.id.sp_mm);
sp_qty = (Spinner)itemView.findViewById(R.id.sp_qty);
// tv_ext_person= (TextView)itemView.findViewById(R.id.tv_ext_person);
ll_extra =(LinearLayout)itemView.findViewById(R.id.ll_extra);
ll_extra_charge =(LinearLayout)itemView.findViewById(R.id.ll_extra_charge);
tv_addtocart= (TextView) itemView.findViewById(R.id.tv_addtocart);
cb_selectedprice =(CheckBox)itemView.findViewById(R.id.cb_selectedprice);
final int position = getAdapterPosition();
String extra_duration_charge = "";
str_id= stList.get(position).getId();
if(stList.get(position).getIs_applicable().equalsIgnoreCase("0")){
itemView.setEnabled(false);
itemView.setClickable(false);
itemView.setBackgroundResource(R.color.md_blue_grey_50);
tv_addtocart.setVisibility(View.GONE);
}
tvName.setText(stList.get(position).getPackage_name());
tv_details.setText(stList.get(position).getChrages_inclusion());
tv_price.setText(" $ "+Const.GLOBAL_FORMATTER.format(Double.parseDouble(stList.get(position).getCharges())));
if(stList.get(position).getPacakage_hours()!=null){
tv_duration.setText(stList.get(position).getPacakage_hours().substring(0,stList.get(position).getPacakage_hours().length()-3)+" hr");
}else{
tv_duration.setVisibility(View.GONE);
}
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1")){
tv_guestCount.setText(stList.get(position).getGroup_size_from()
+"-"
+stList.get(position).getGroup_size_to() +" Guest");
}else{
tv_guestCount.setVisibility(View.GONE);
}
//======EXTRA GUEST AND TIME CONDITION FOR TEXT VIEW ==========================================
if(stList.get(position).getIs_hour_extension_charges()!=null) {
if(stList.get(position).getIs_hour_extension_charges().equalsIgnoreCase("1")){
ll_extra_charge.setVisibility(View.VISIBLE);
if (stList.get(position).getExtension_hours().substring(0, 2).equalsIgnoreCase("00")) {
extra_duration_charge = "$ " + stList.get(position).getHour_extension_charges() + " / " + stList.get(position).getExtension_hours().substring(3, 5) + " min";
} else {
extra_duration_charge = "$ " + stList.get(position).getHour_extension_charges() + " / " + stList.get(position).getExtension_hours().substring(0, 5) + " hours";
}
tv_extra_charge.setText(extra_duration_charge);
}
}
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1") && stList.get(position).getIs_extra_person_charges().equalsIgnoreCase("1")){
extra_duration_charge = extra_duration_charge+"\n"+"$"+stList.get(position).getIs_extra_person_charges()+"/ person";
tv_extra_charge.setText(extra_duration_charge);
}
if(extra_duration_charge==null || extra_duration_charge.length()<1){
ll_extra_charge.setVisibility(View.GONE);
if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Flat Rate");
} else if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Per Person");
} else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")) {
tv_pkg_rate.setText("Per Hour");
}
}else{
if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Flat Rate");
} else if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
tv_pkg_rate.setText("Per Person");
} else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")) {
tv_pkg_rate.setText("Per Hour");
}
}
//==========FLAT PER PERSON PER HOURE CHARGES CONDITION======================================================
if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
ll_extra.setVisibility(View.INVISIBLE);
// tv_ext_person.setVisibility(View.GONE);
} else if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1") && stList.get(position).getExtra_person_charges()!=null){
ll_extra.setVisibility(View.VISIBLE);
img_clock.setVisibility(View.GONE);
sp_hh.setVisibility(View.GONE);
//np_itemcount.setVisibility(View.VISIBLE);
// tv_ext_person.setVisibility(View.VISIBLE);
//np_itemcount.setMaxValue(Integer.parseInt(stList.get(position).getGroup_size_to()));
}else{
ll_extra.setVisibility(View.INVISIBLE);
//tv_ext_person.setVisibility(View.GONE);
}
if(stList.get(position).getIs_extra_person_charges().equalsIgnoreCase("0")){
ll_extra.setVisibility(View.INVISIBLE);
//tv_ext_person.setVisibility(View.GONE);
}
}else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")) {
ll_extra.setVisibility(View.VISIBLE);
img_guest.setVisibility(View.GONE);
sp_qty.setVisibility(View.GONE);
//ll_duration.setVisibility(View.GONE);
}
List<String> list_hh = new ArrayList<String>();
list_hh.add("HH");
list_hh.add("01");
list_hh.add("02");
list_hh.add("03");
list_hh.add("04");
list_hh.add("05");
list_hh.add("06");
list_hh.add("07");
list_hh.add("08");
list_hh.add("09");
list_hh.add("10");
list_hh.add("11");
list_hh.add("12");
ArrayAdapter<String> dataAdapter_hh = new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, list_hh);
dataAdapter_hh.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_hh.setAdapter(dataAdapter_hh);
List<String> list_mm = new ArrayList<String>();
list_mm.add("MM");
list_mm.add("00");
list_mm.add("15");
list_mm.add("30");
list_mm.add("45");
ArrayAdapter<String> dataAdapter_mm = new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, list_mm);
dataAdapter_mm.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_mm.setAdapter(dataAdapter_mm);
List<String> list_qty = new ArrayList<String>();
list_qty.add("Guest");
for(int a=0;a<100;a++){
list_qty.add(Integer.toString(a));
}
ArrayAdapter<String> dataAdapter_qty = new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, list_qty);
dataAdapter_qty.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_qty.setAdapter(dataAdapter_qty);
sp_hh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int positionSP, long id) {
if(sp_mm.getSelectedItemPosition()>1 && positionSP>1){
final_total = Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) * (double) (sp_hh.getSelectedItemPosition() +1) );
}else{
if(positionSP > 1) {
final_total = Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) * (double) (sp_hh.getSelectedItemPosition()));
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
}
}
/* Toast.makeText(parent.getContext(), "Time : " +
sp_hh.getItemAtPosition(sp_hh.getSelectedItemPosition()).toString()
+ ":"
+String.valueOf(sp_mm.getSelectedItem()), Toast.LENGTH_SHORT).show();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
sp_mm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int positionSP, long id) {
if(positionSP>1){
final_total = Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) *(double) (sp_hh.getSelectedItemPosition() + 1 ));
// tv_menutitle_venuepricing.setText("Pricing Plans "+" ( Total : "+final_total+" )");
}else{
if(sp_hh.getSelectedItemPosition()>0){
final_total =Double.parseDouble(stList.get(position).getCharges())+(Double.parseDouble(stList.get(position).getCharges()) * (double) (sp_hh.getSelectedItemPosition()));
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
}
}
/*Toast.makeText(parent.getContext(), "Time : " + sp_hh.getItemAtPosition(sp_hh.getSelectedItemPosition()).toString()
+ ":" +sp_mm.getItemAtPosition(sp_mm.getSelectedItemPosition()).toString(), Toast.LENGTH_SHORT).show();*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/*chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(chkSelected.isChecked()==true){
checked_count=checked_count+1;
if(checked_count > 1){
chkSelected.setChecked(false);
checked_count=checked_count-1;
Log.d("chk count ",""+checked_count);
}else {
Log.d("chk count",""+checked_count);
if(stList.get(position).getIs_perperson_charges().equalsIgnoreCase("1")){
final_total = Double.parseDouble(stList.get(position).getCharges()) * Double.parseDouble(et_guestCount.getText().toString());
// tv_menutitle_venuepricing.setText("Pricing Plans "+" ( Total : "+final_total+" )");
}else if(stList.get(position).getIs_perhour_charges().equalsIgnoreCase("1")){
if(np_minutes_venue_pkg.getValue()>0){
final_total = Double.parseDouble(stList.get(position).getCharges()) * (double)(np_hour_venue_pkg.getValue()+1);
// tv_menutitle_venuepricing.setText("Pricing Plans "+" ( Total : "+final_total+" )");
}else{
if(np_hour_venue_pkg.getValue()>0) {
final_total = Double.parseDouble(stList.get(position).getCharges()) * (double) (np_hour_venue_pkg.getValue());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
//tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}
}
selected_hr= Integer.toString(np_hour_venue_pkg.getValue());
if(selected_hr.length()<=1){
selected_hr="0"+selected_hr;
}
selected_min=Integer.toString(np_minutes_venue_pkg.getValue());
if(selected_min.length()<=1){
selected_min="0"+selected_min;
}
}else if(stList.get(position).getIs_flat_charges().equalsIgnoreCase("1")){
if(stList.get(position).getIs_group_charges().equalsIgnoreCase("1") && stList.get(position).getIs_extra_person_charges().equalsIgnoreCase("1") ){
int guest_from =Integer.parseInt(stList.get(position).getGroup_size_from());
int guest_to =Integer.parseInt(stList.get(position).getGroup_size_to());
int guest =Integer.parseInt(et_guestCount.getText().toString());
if(guest>guest_to){
int extra_guest = guest-guest_to;
final_total = ((double)extra_guest * Double.parseDouble(stList.get(position).getExtra_person_charges()) )
+Double.parseDouble(stList.get(position).getCharges());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : " + Const.GLOBAL_FORMATTER.format(final_total) + " )");
}else{
final_total = Double.parseDouble(stList.get(position).getCharges());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}
}else {
final_total = Double.parseDouble(stList.get(position).getCharges());
// tv_menutitle_venuepricing.setText("Pricing Plans " + " ( Total : "+ Const.GLOBAL_FORMATTER.format(final_total) + " )");
}
}
}
}else{
checked_count=checked_count-1;
Log.d("chk count",""+checked_count);
if(checked_count==0){
// tv_menutitle_venuepricing.setText("Pricing Plans ");
}
}
VenueOrderPriceModel contact = (VenueOrderPriceModel) chkSelected.getTag();
contact.setSelected(chkSelected.isChecked());
stList.get(getAdapterPosition()).setSelected(chkSelected.isChecked());
*//*Toast.makeText(
chkSelected.getContext(),
"Clicked on Checkbox: " + chkSelected.getText() + " is "
+ chkSelected.isChecked(), Toast.LENGTH_LONG).show();*//*
}
});*/
if (cb_selectedprice.isChecked()==true){
img_remove.setVisibility(View.VISIBLE);
}else{
img_remove.setVisibility(View.GONE);
}
img_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isPkgAdded=false;
cb_selectedprice.setChecked(false);
img_remove.setVisibility(View.GONE);
tv_addtocart.setBackground(mContext.getResources().getDrawable(R.drawable.rounded_corner_orange_white_borde,mContext.getTheme()));
tv_addtocart.setEnabled(true);
final_total=0;
}
});
tv_addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPkgAdded == true || cb_selectedprice.isChecked()==true) {
Toast.makeText(mContext, "First Remove Added Pacakge", Toast.LENGTH_LONG).show();
} else {
Log.e("boooking details --",str_dateselected+str_guest_count+str_timeslot);
}
}
});
}
}
// method to access in activity after updating selection
public List<VenueOrderPriceModel> getStudentist() {
return stList;
}
}
You have to maintain the state of each checkbox in you data model from onCheckChangeListener of checkbox wrt every positions.
Then you have to set the checkbox state in onBind method of adapter
The recycler view recycles the view in OnBindViewHolder. So when items are scrolled view is recycled again.To solve this.
create a global variable to store the clicked position.
private mItemSelected=-1;
Then inside viewholder add the clickListener and onClick store the position of the clicked item.
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mItemSelected = getAdapterPosition();
notifyDataSetChanged();
}
});
}
}
And in inside OnBindViewHolder,
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(mItemSelected==position){
holder.status.setChecked(true);
}else{
holder.status.setChecked(false);
}
}
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 want to implement the reclyerview to behave like following
items by default will be grey color and the other button hidden until on button add click:
The expansion happens one item per list if any other item is expanded clicking on the next item will first close any open item and then open the new one:
I have tried to implement it but every time a single item clicked and the expansion occurs, then no other item in the list will expand even though clicking on the plus button increases the number on it.
Also the expansion can appear on all items while on the reference its only one item per click that expands.
Here is my code
public class SalesProductsAdapter extends
RecyclerView.Adapter<SalesProductsAdapter.Vh>
implements
TextWatcher,Filterable,View.OnClickListener,AdapterView.OnItemClickListener
{
public List<SalesProductsItems> mItems = new ArrayList<SalesProductsItems>();
public static List<SalesProductsItems> filteredIt = new ArrayList<SalesProductsItems>();
#Override
public Vh onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.selling_screen_sellitems, parent, false);
Vh vh = new Vh(v);
return vh;
}
#Override
public void onBindViewHolder(final Vh holder, final int position) {
final SalesProductsItems cl = filteredIt.get(position);
if(pitems != null && pitems.size() > 0){
for(int j = 0; j < pitems.size(); j++){
Pending_Items _pitems = pitems.get(j);
long proid = cl.getProdid();
long _proid = _pitems.getProdloc();
if(proid == _proid){
prodname = cl.getProduct();
qty[0] = new BigDecimal(_pitems.getQty()).intValue();
unit[0] = _pitems.getPrice();
} else {
prodname = cl.getProduct();
qty[0] = new BigDecimal(cl.getQuantity()).intValue();
unit[0] = cl.getUnit();
}
}
} else {
prodname = cl.getProduct();
qty[0] = new BigDecimal(cl.getQuantity()).intValue();
unit[0] = cl.getUnit();
}
items = pitems.size();
if(items > 0)
imgnext.setVisibility(View.VISIBLE);
else
imgnext.setVisibility(View.GONE);
holder.txtproduct.setText(prodname);
updateViews(qty[0], holder);
if(qty[0] > 0){
System.out.println(" qty is " + s_qty);
holder.imgminus.setVisibility(View.GONE);
holder.imgadd.setVisibility(View.GONE);
holder.txtqty.setText(s_qty[0]);
holder.txtunit.setText(s_unit);
holder.txtsubtotal.setText(s_subtotal[0]);
} else {
holder.imgminus.setVisibility(View.GONE);
holder.txtqty.setVisibility(View.GONE);
holder.txtunit.setText(s_unit);
holder.txtsubtotal.setVisibility(View.GONE);
}
holder.imgadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
qty[0] += 1;
if(Products.checkQty(context,cl.getProdid(),qty[0])) {
if (qty[0] == 1) {
s_qty[0] = String.valueOf(qty[0]);
holder.txtqty.setText(s_qty[0]);
holder.txtqty.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
process_item(cl, holder,position);
changeBg(holder,qty[0]);
holder.txtsubtotal.setVisibility(View.VISIBLE);
} else {
s_qty[0] = String.valueOf(qty[0]);
holder.txtqty.setText(s_qty[0]);
process_item(cl, holder,position);
holder.txtsubtotal.setVisibility(View.VISIBLE);
}
} else {
Toast.makeText(context,cl.getProduct() + " " + context.getResources().getString(R.string
.strsalesquantityerror1) +
" " + Products.getItemOnHand(context,String.valueOf(cl.getProdid())) + " " + context.getResources()
.getString(R.string.strsalesquantityerror2), Toast.LENGTH_LONG).show();
}
}
});
holder.layview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.imgminus.getVisibility() == View.VISIBLE){
holder.imgminus.setVisibility(View.GONE);
if(qty[0] == 0) {
holder.imgadd.setVisibility(View.VISIBLE);
holder.txtqty.setVisibility(View.GONE);
}
else {
holder.txtqty.setVisibility(View.VISIBLE);
holder.imgadd.setVisibility(View.GONE);
holder.txtqty.setText(s_qty[0]);
}
} else {
Intent intent = new Intent(context,SingeItem.class);
intent.putExtra(Constants.SOURCE,Constants.SALETYPE_SALE);
intent.putExtra(Products.PRODUCTNAME,cl.getProdid());
intent.putExtra(Products.ID, position);
context.startActivity(intent);
}
}
});
holder.txtqty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.imgadd.getVisibility() == View.GONE){
holder.txtqty.setText(s_qty[0]);
holder.imgadd.setVisibility(View.VISIBLE);
holder.imgminus.setVisibility(View.VISIBLE);
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return filteredIt.size();
}
#Override
public long getItemId(int arg0){
return 0;
}
private void updateViews(int qt, Vh holder){
double un = unit[0];
double st = new BigDecimal(qt).multiply(new BigDecimal(un)).doubleValue();
s_qty[0] = String.valueOf(qt);
s_subtotal[0] = new BigDecimal(st).setScale(2, RoundingMode.HALF_UP).toString();
s_subtotal[0] = currency + " " + new BigDecimal(subtotal[0]).setScale(2, RoundingMode.HALF_UP).toString();
s_unit = currency+" "+new BigDecimal(unit[0]).setScale(2, RoundingMode.HALF_UP).toString();
holder.txtsubtotal.setText(s_subtotal[0]);
holder.txtunit.setText(s_unit);
holder.txtsubtotal.setVisibility(View.VISIBLE);
if(qt > 0)
imgnext.setVisibility(View.VISIBLE);
else
imgnext.setVisibility(View.GONE);
gtotal += subtotal[0];
txtt.setText(currency + " " + new BigDecimal(gtotal).setScale(2, RoundingMode.HALF_UP).toString());
txti.setText("/ " + items + " " + context.getString(R.string.stritems));
}
}
1) At a time if you want to show/hide only one element this one work fine
Step1)
create a variable and set its value to=-1;
int currentPosition=-1;
Step2)
On bind viewHolder,on itemClick update currentPosition to holder position
onBindViewHolder(ViewHolder v,int position)
{
view.Onclick(...{currentPosition=position;});
if(currentPosition==position)
view.setVisiblity(Visible);
else
view.setVisibility(Gone);
}
2) If you want to show more item on any button click then
Create 2 arrayList,first arrayList store total value and second
arrayList display only few elements in holder;
now on button click add all element to other arrayList and notify.
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));`