Apply Listener on some ListView columns - android

Background:
I have created a ListView with three columns sNo, product and price. First column is defined as TextView (whose value is auto generated) and the next two columns are EditText (whose value is filled up by the user).
What I want:
I want to add a new row to the ListView whenever:
User hit enter key on any EditText
There is no empty EditText (meaning all the EditText defined so far have some value in them).
Basically I want display a new orders list where users can add orders.
My code so far:
ListView Model:
public class NewTableModel {
private String sNo, product, price;
public NewTableModel(String sNo, String product, String price){
this.sNo = sNo;
this.product = product;
this.price = price;
}
public String getProduct(){ return product; }
public String getPrice(){ return price; }
public String getsNo() { return sNo; }
}
ListView adapter:
public class NewTableAdapter extends BaseAdapter {
private ArrayList<NewTableModel> productList;
private Activity activity;
public NewTableAdapter(Activity activity, ArrayList<NewTableModel> productList) {
super();
this.activity = activity;
this.productList = productList;
}
#Override
public int getCount() { return productList.size(); }
#Override
public Object getItem(int position) { return productList.get(position); }
#Override
public long getItemId(int position) { return position; }
public class ViewHolder {
TextView mSno;
EditText mProduct;
EditText mPrice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.new_table_row, null);
holder = new ViewHolder();
holder.mSno = (TextView) convertView.findViewById(R.id.sno);
holder.mProduct = (EditText) convertView.findViewById(R.id.product);
holder.mPrice = (EditText) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
NewTableModel item = productList.get(position);
holder.mSno.setText(item.getsNo());
holder.mProduct.setText(item.getProduct());
holder.mPrice.setText(String.valueOf(item.getPrice()));
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayList<NewTableModel> productList;
private ListView orderView;
private NewTableAdapter orderAdapter;
private void insertNewRow(){ insertNewRow("",""); }
private void insertNewRow(String productVal, String priceVal){
String serialNoVal = String.valueOf(orderView.getCount() + 1);
NewTableModel item = new NewTableModel(serialNoVal, productVal, priceVal);
productList.add(item);
}
private void setupAdapter(){
productList = new ArrayList<NewTableModel>();
orderView = (ListView) findViewById(R.id.newTableContent);
orderAdapter = new NewTableAdapter(this, productList);
orderView.setAdapter(orderAdapter);
orderAdapter.notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setupAdapter();
insertNewRow();
}
}
My Listener:
setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
&& noEmptyColumn())
insertNewRow();
return false;
}
});
Where should I place that listener ? and how would I check if any column is empty or not (define noEmptyColumn()) ?

You should place the listener where any of EditText values are changed. I would add a Button to any row, and set the listener at there. So in your ViewHolder:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean hasEmpty = false;
for (NewTableModel item: productList) {
if (item.getDesiredField().isEmpty()) {
hasEmpty = true;
break;
}
}
if (!hasEmpty) {
insertNewRow();
notifyDataSetChanged();
}
}
});
Another option could be setting a TextWatcher on EditText :
ed.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
boolean hasEmpty = false;
for (NewTableModel item: productList) {
if (item.getDesiredField().isEmpty()) {
hasEmpty = true;
break;
}
}
if (!hasEmpty) {
insertNewRow();
notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Just move both methods to your Adapter class. And note that the second solution is not efficient when there are too many rows.

Related

Clear EditText value in a RecyclerView row

I have a RecyclerView in my android project. There I am adding rows from searching from a AutoCompleteTextView. Each row has TextView and one EditText field. As well as adding, I am also removing rows. I have a remove button in a each row.
Everything works fine. Problem is I cannot clear EditText value in removing. For example if I add three rows and remove the second one, the third row should come to second place with its own EditText value. But the problem is, the value from the row removed is not clearing and the third row's EditText value is replaced by it instead. Then if I add another row (to the third place), automatically that EditText field is filled with previous third row's EditText value.
How can I clear EditText value also???
This is my adapter code.
public class SelectItemAdapter extends RecyclerView.Adapter<SelectItemAdapter.ItemHolder> {
private List<String> itemsName, itemsQty, itemsPCode, itemPlant, _retData;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
private String[] mDataset;
public ArrayList myItems = new ArrayList();
private Context context;
private String[] arrayForSaveEditTextValue;
public SelectItemAdapter(Context context, String[] mDataset) {
layoutInflater = LayoutInflater.from(context);
itemsName = new ArrayList<String>();
itemsQty = new ArrayList<String>();
itemsPCode = new ArrayList<String>();
itemPlant = new ArrayList<String>();
_retData = new ArrayList<String>();
this.arrayForSaveEditTextValue = mDataset;
}
#Override
public SelectItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.custom_row_selected_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(final SelectItemAdapter.ItemHolder holder, final int position) {
holder.setItemName(itemsName.get(position));
holder.setItemQty(itemsQty.get(position));
holder.setItemPCode(itemsPCode.get(position));
holder.setItemPlant(itemPlant.get(position));
holder.numPicker.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {}
#Override
public void afterTextChanged(Editable arg0) {
_retData.set(position, arg0.toString());
Log.d("arg0",arg0.toString());
}
});
}
#Override
public int getItemViewType(int position) {
return position;
}
public String retrieveData(int i) {
return _retData.get(i);
}
#Override
public int getItemCount() {
return itemsName.size();
}
public Object getItemName(int position) {
return itemsName.get(position);
}
public Object getItemQty(int position) {
return itemsQty.get(position);
}
public Object getItemPCode(int position) {
return itemsPCode.get(position);
}
public Object getItemPlant(int position) {
return itemPlant.get(position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public interface OnItemClickListener {
public void onItemClick(ItemHolder item, int position);
}
public void add(int location, String iName, String iQty, String iPCode, String iPlant) {
itemsName.add(location, iName);
itemsQty.add(location, iQty);
itemsPCode.add(location, iPCode);
itemPlant.add(location, iPlant);
_retData.add(location,"0");
notifyItemInserted(location);
notifyDataSetChanged();
}
public void remove(int location) {
if (location >= itemsName.size())
return;
itemsName.remove(location);
itemsQty.remove(location);
itemsPCode.remove(location);
itemPlant.remove(location);
_retData.remove(location);
notifyItemRemoved(location);
notifyDataSetChanged();
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private SelectItemAdapter parent;
TextView textItemName, txtPCode, txtAvailableQty, txtTempQty, txtPlant;
Button bRemove;
EditText numPicker;
public ItemHolder(View itemView, SelectItemAdapter parent) {
super(itemView);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.txtProductName);
txtAvailableQty = (TextView) itemView.findViewById(R.id.txtAvailbleQty);
txtPCode = (TextView) itemView.findViewById(R.id.txtPCode);
txtPlant = (TextView) itemView.findViewById(R.id.txtPlant);
bRemove = (Button) itemView.findViewById(R.id.bRemove);
numPicker = (EditText) itemView.findViewById(R.id.numberPicker);
bRemove.setOnClickListener(this);
}
public void setItemName(CharSequence name) {
textItemName.setText(name);
}
public void setItemQty(CharSequence name) {
txtAvailableQty.setText(name);
}
public void setItemPCode(CharSequence name) {
txtPCode.setText(name);
}
public void setItemPlant(CharSequence name) {
txtPlant.setText(name);
}
public CharSequence getItemName() {
return textItemName.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if (listener != null) {
listener.onItemClick(this, getPosition());
}
}
}
public class RetItem {
public String _itemNumPic;
}
}
And the remove method...
#Override
public void onItemClick(SelectItemAdapter.ItemHolder item, int position) {
Toast.makeText(this,
"Remove " + " : " + item.getItemName(),
Toast.LENGTH_SHORT).show();
myRecyclerViewAdapter.remove(position);
}
First of all use a list of an Object instead of using lots of string arrays!
and then to achieve the behavior you want, you need to remove the item from the main list and call notifyDataSetChanged();
Here is an ex:
List<DayEntity> days = new ArrayList<>();
Here is a list of day items, you set this list to your adapter like this:
MyDayAdapter adapter = new MyDayAdapter(context, days);
So for removing an item in position 'x' you can do this way:
days.remove(x);
adapter.notifyDataSetChanged();
have fun...
1- Create a model class for your data, with all your getters and setters in one list:
public class SelectItemAdapter extends RecyclerView.Adapter<SelectItemAdapter.ItemHolder> {
private final ArrayList<MyData> mDataList = new ArrayList<>();
2- remove at method
//Remove from the list on click
private void removeAt(int position) {
mUserList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataList.size());
}
3- Now inside onClick() method you can call removeAt method, and you just pass the position which is the adapter position
removeAt(getAdapterPosition());
You need to keep track of the values entered in the EditText of your RecyclerView. You've an array named arrayForSaveEditTextValue for saving the EditText values I think, but I see no usage of it. Your code is a little bit clumsy too. So I would like to suggest a different approach of implementing this list for you.
Create an object for your list items.
public class ListItem {
public String itemsName;
public String itemsQty;
public String itemsPCode;
public String itemPlant;
public String _retData;
public String editTextValue = ""; // Default EditText Value
}
And your adapter should look like this.
public class SelectItemAdapter extends RecyclerView.Adapter<SelectItemAdapter.ItemHolder> {
private List<ListItem> listItems;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
public SelectItemAdapter(Context context, List<ListItem> listItems) {
layoutInflater = LayoutInflater.from(context);
this.listItems = listItems;
}
#Override
public SelectItemAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.custom_row_selected_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(final SelectItemAdapter.ItemHolder holder, final int position) {
final ListItem tempListItem = listItems.get(position);
holder.textItemName.setText(tempListItem.itemsName);
holder.txtAvailableQty.setText(tempListItem.itemsQty);
holder.txtPCode.setText(tempListItem.itemsPCode);
holder.txtPlant.setText(tempListItem.itemPlant);
holder.numPicker.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
// Calculate your _retData and set the TextView
tempListItem._retData = calculateRetData(position, arg0.toString());
tempListItem.editTextValue = arg0.toString();
// Replace the item with the value updated
listItems.add(position, tempListItem);
notifyDataSetChanged();
}
});
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return listItems.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public interface OnItemClickListener {
public void onItemClick(ItemHolder item, int position);
}
public void add(ListItem listItem) {
listItems.add(listItem);
notifyDataSetChanged();
}
public void remove(int location) {
if (location >= listItems.size())
return;
listItems.remove(location);
notifyDataSetChanged();
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private SelectItemAdapter parent;
TextView textItemName, txtPCode, txtAvailableQty, txtTempQty, txtPlant;
Button bRemove;
EditText numPicker;
public ItemHolder(View itemView, SelectItemAdapter parent) {
super(itemView);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.txtProductName);
txtAvailableQty = (TextView) itemView.findViewById(R.id.txtAvailbleQty);
txtPCode = (TextView) itemView.findViewById(R.id.txtPCode);
txtPlant = (TextView) itemView.findViewById(R.id.txtPlant);
bRemove = (Button) itemView.findViewById(R.id.bRemove);
numPicker = (EditText) itemView.findViewById(R.id.numberPicker);
bRemove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if (listener != null) {
listener.onItemClick(this, getPosition());
}
}
}
}
The idea is to save the EditText value in the corresponding object and in case of adding and deleting an item from the RecyclerView, you have to update the list of the items accordingly and then call notifyDataSetChanged().
I haven't tested the code, but I think you get the idea. Please let me know if there's anything else I can help you with.

i have an issue with checked textview

i have used checked textview with base adapter to fill listview it's working fine but when i try to scroll CheckedTextView lost the selection.please find the code bellow and help me.
public class AttendancePage extends AppCompatActivity {
List<String> studentNames = new ArrayList<String>();
String[] sNames;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
databaseHelper = new DatabaseHelper(getApplicationContext());
Cursor res = databaseHelper.getStudentNames();
setTitle("Attendance Sheet");
ListView listView = (ListView) findViewById(R.id.listView);
while (res.moveToNext()) {
studentNames.add(res.getString(0));
}
sNames = new String[studentNames.size()];
sNames = studentNames.toArray(sNames);
Student_Attandence_Addapter customAdapter = new Student_Attandence_Addapter(getApplicationContext(), sNames);
listView.setAdapter(customAdapter);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
My custom Adapter class:
public class Student_Attandence_Adapter extends BaseAdapter {
String[] names;
Context context;
LayoutInflater inflter;
String value;
public Student_Attandence_Adapter(Context context, String[] names) {
this.context = context;
this.names = names;
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(names[position]);
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
value = "un-Checked";
simpleCheckedTextView.setCheckMarkDrawable(0);
simpleCheckedTextView.setChecked(false);
} else {
value = "Checked";
simpleCheckedTextView.setCheckMarkDrawable(R.drawable.checked);
simpleCheckedTextView.setChecked(true);
}
}
});
return view;
}
}
Basically what happens is the state of the ChekedTextView will be reset whenever the getView method will be called according to the previous cached state of the list item. So in short you need to store the checked state of an item and when the getView method will be called you need to set it again. For example you need an object containing name and checked state
public class Student {
private String name;
private boolean checked;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
}
and your getView method will be like this,
#Override
public View getView(int position, View view, ViewGroup parent) {
/*
* ListView caches the view so only inflate when there
* is no cached view aka null
*/
if (view == null) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
}
Student aStudent = students[position];
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(aStudent.getName());
simpleCheckedTextView.setCheckMarkDrawable(aStudent.isChecked() ? R.drawable.checked : 0);
simpleCheckedTextView.setChecked(aStudent.isChecked());
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
aStudent.setChecked(false);
notifyDataSetChanged();
} else {
aStudent.setChecked(true);
notifyDataSetChanged();
}
}
});
return view;
}
That's the theme. Modify it as you need.

ExpandableRecyclerAdapter How to force item to move up while expanding an item

This is my ExpandableRecyclerAdapter adapter
public class MyAdapter extends ExpandableRecyclerAdapter<MyAdapter.ProductParentViewHolder, MyAdapter.ProductChildViewHolder> {
private LayoutInflater mInflater;
private Context context;
private List<? extends ParentListItem> mParentItemList;
public MyAdapter(Context context, List<ParentListItem> itemList) {
super(itemList);
mInflater = LayoutInflater.from(context);
this.context = context;
this.mParentItemList = itemList;
}
#Override
public ProductParentViewHolder onCreateParentViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_parent, viewGroup, false);
return new ProductParentViewHolder(view);
}
#Override
public ProductChildViewHolder onCreateChildViewHolder(ViewGroup viewGroup) {
View view = mInflater.inflate(R.layout.list_item_crime_child, viewGroup, false);
return new ProductChildViewHolder(view);
}
#Override
public void onBindParentViewHolder(ProductParentViewHolder crimeParentViewHolder, int i, ParentListItem parentListItem) {
Product product = (Product) parentListItem;
crimeParentViewHolder.productName.setText(product.getBrandName() + " " + product.getProductName());
Glide.with(context)
.load(product.getProductImagePath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(crimeParentViewHolder.thumbnail);
}
#Override
public void onBindChildViewHolder(ProductChildViewHolder productChildViewHolder, int i, Object childListItem) {
final ProductVariant productVariant = (ProductVariant) childListItem;
productChildViewHolder.mCrimeDateText.setText(productVariant.getVariantName());
productChildViewHolder.variantMrp.setText(context.getString(R.string.positive_amount, productVariant.getMRP()));
productChildViewHolder.variantMrp.setPaintFlags(productChildViewHolder.variantMrp.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
productChildViewHolder.variantSellPrice.setText(context.getString(R.string.positive_amount, productVariant.getSellPrice()));
//productChildViewHolder.variantMrp.setText(productVariant.getMRP().toString());
//productChildViewHolder.variantSellPrice.setText(productVariant.getSellPrice().toString());
if (productVariant.getInCart() == 0) {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.GONE);
} else {
productChildViewHolder.btnProductDetailAddToCart.setVisibility(View.GONE);
productChildViewHolder.btnProductDetailMinus.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailQty.setVisibility(View.VISIBLE);
productChildViewHolder.btnProductDetailPlus.setVisibility(View.VISIBLE);
}
int quantity = productVariant.getInCart();
productChildViewHolder.btnProductDetailQty.setText(Integer.toString(quantity));
productChildViewHolder.btnProductDetailAddToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1);
//Utility.loadShoppingCartItems();
notifyDataSetChanged();
invalidateOptionsMenu();
//holder.db.addItem(new CartItem(1, productVariant.getProductID(), productVariant.getVariantID(), 1));
}
});
productChildViewHolder.btnProductDetailPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(1 + productVariant.getInCart());
notifyDataSetChanged();
invalidateOptionsMenu();
//if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
//}
}
});
productChildViewHolder.btnProductDetailMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productVariant.setInCart(productVariant.getInCart() - 1);
notifyDataSetChanged();
invalidateOptionsMenu();
if (productVariant.getInCart() == 0) {
//int count = holder.db.deleteSingleRow(productVariant.getProductID(), productVariant.getVariantID());
} else if (productVariant.getInCart() > 0) {
//int count = holder.db.updateSingleRow(productVariant.getProductID(), productVariant.getVariantID(), productVariant.getInCart());
}
//Utility.displayToast(holder.db.getItemsCount() + "");
}
});
//crimeChildViewHolder.mCrimeSolvedCheckBox.setChecked(productVariant.isSolved());
}
public class ProductParentViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
private final boolean HONEYCOMB_AND_ABOVE = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
public TextView productName;
public ImageView thumbnail;
public ImageButton mParentDropDownArrow;
public ProductParentViewHolder(View itemView) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.productName);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
// mParentDropDownArrow = (ImageButton) itemView.findViewById(R.id.parent_list_item_expand_arrow);
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (!HONEYCOMB_AND_ABOVE) {
return;
}
if (expanded) {
// mParentDropDownArrow.setRotation(ROTATED_POSITION);
} else {
// mParentDropDownArrow.setRotation(INITIAL_POSITION);
}
}
}
public class ProductChildViewHolder extends ChildViewHolder {
public TextView mCrimeDateText;
public TextView variantMrp;
public TextView variantSellPrice;
public Button btnProductDetailAddToCart, btnProductDetailPlus, btnProductDetailMinus;
public TextView btnProductDetailQty;
public ProductChildViewHolder(View itemView) {
super(itemView);
mCrimeDateText = (TextView) itemView.findViewById(R.id.variantName);
variantMrp = (TextView) itemView.findViewById(R.id.productVariantMrp);
variantSellPrice = (TextView) itemView.findViewById(R.id.productVariantSellPrice);
btnProductDetailAddToCart = (Button) itemView.findViewById(R.id.btnProductDetailAddToCart);
btnProductDetailPlus = (Button) itemView.findViewById(R.id.btnProductDetailPlus);
btnProductDetailMinus = (Button) itemView.findViewById(R.id.btnProductDetailMinus);
btnProductDetailQty = (TextView) itemView.findViewById(R.id.btnProductDetailQty);
}
}
}
When i am bottom of the page and click on item it expands, but exapnded child item doesn't shows to user because it is bottom in the screen.
I want to move that item up in the screen and show expanded items to user.
How can i do that?
You can simply use the method setSelectedGroup()
expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
expandableListView.setSelectedGroup(groupPosition);
return true;
}
});
This will move the selected group to the top
EDIT
Finally I came out with a solution for your ExpandableRecyclerAdapter also. Simply put this method inside your adapter implementation. Also you will require the reference of the recyclerView inside the adapter which you can pass to the adapter at the time of initialization.
int lastPos = -1;
#Override
public void onParentListItemExpanded(int position) {
List<? extends ParentListItem> parentItemList = this.getParentItemList();
collapseAllParents();
int finalPos = position;
if (lastPos != -1 && lastPos < position) {
finalPos = position - parentItemList.get(lastPos).getChildItemList().size();
}
expandParent(finalPos);
mRecyclerView.smoothScrollToPosition(finalPos);
lastPos = position;
}
I found this issue at https://github.com/bignerdranch/expandable-recycler-view/issues/156 . Although the solution given there didn't work. Slight tweaking to that make it work.
Use this following code in your expandable listview click listener. Do something liket his
yourExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onGroupClick(final ExpandableListView parent, View v, final int groupPosition, long id) {
....
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
parent.smoothScrollToPositionFromTop(groupPosition + 1, 0);
}
},100);
....
return true;
}
});
Use AnimatedExpandableListView

How to make a right interaction between custom adapters in android?

I write a simple test code about shopping. It's like in the picture.add from right to left
It's simple. ListViews show 'Item's. The 'Item' has only name and count. On the right, I change the count and add the item to the cart on the left.
The main point is here, when I change the item's count that I added earlier and add the item again to the cart, all the same items in the cart and in the menu changes to the last count.
After I took the first picture, I changed the same item's count and added it again. So, two items in the cart have same last count. I can't understand the mistake in the code. Second screenshot after added the same item with different count
Thanks in advance.
I found something about the code. All the ArrayLists are acting like they are static. If I change the onClick metot of add button in the menu as:
ImageButton ekle = (ImageButton) view.findViewById(R.id.imageButton2);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//After changing this row, all the ArrayList's (menu and cart) items
//in this position is changing to the same number 5.
//And I delete the EditText's TextChangeListener, as well.
menu.get(position).setCount(5);
((BaseAdapter) context.list1.getAdapter()).notifyDataSetChanged();
}
});
public class Item {
private String name;
private int count;
public Item(String s, int i) {
name = s;
count = i;
}
public String getName() {return name;}
public int getCount() {return count;}
public void setName(String s) {name = s;}
public void setCount(int i) {count = i;}
}
public class MainActivity extends AppCompatActivity {
ListView list1;
ListView list2;
static ArrayList<Item> menu = new ArrayList<>();
static ArrayList<Item> cart = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu.add(new Item("Item1", 1));
menu.add(new Item("Item2", 1));
menu.add(new Item("Item3", 1));
menu.add(new Item("Item4", 1));
menu.add(new Item("Item5", 1));
list1 = (ListView) findViewById(R.id.list1);
list1.setAdapter(new CartAdapter(this, cart));
list2 = (ListView) findViewById(R.id.list2);
list2.setAdapter(new MenuAdapter(this, menu));
}
}
public class CartAdapter extends BaseAdapter {
MainActivity context;
ArrayList<Item> cart;
public CartAdapter(Activity activity, ArrayList<Item> m) {
context = (MainActivity) activity;
cart = m;
}
#Override
public int getCount() {
return cart.size();
}
#Override
public Object getItem(int position) {
return cart.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_list, null);
TextView name = (TextView) view.findViewById(R.id.textView);
name.setText(cart.get(position).getName());
EditText count = (EditText) view.findViewById(R.id.editText);
count.setText("" + cart.get(position).getCount());
return view;
}
}
public class MenuAdapter extends BaseAdapter {
MainActivity context;
ArrayList<Item> menu;
public MenuAdapter(Activity activity, ArrayList<Item> m) {
context = (MainActivity) activity;
menu = m;
}
#Override
public int getCount() {
return menu.size();
}
#Override
public Object getItem(int position) {
return menu.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_list2, null);
ImageButton ekle = (ImageButton) view.findViewById(R.id.imageButton2);
ekle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.cart.add(menu.get(position));
((BaseAdapter) context.list1.getAdapter()).notifyDataSetChanged();
}
});
TextView name = (TextView) view.findViewById(R.id.textView2);
name.setText(menu.get(position).getName());
EditText miktar = (EditText) view.findViewById(R.id.editText2);
miktar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count != 0) {
int i = Integer.parseInt(s.toString());
Item item = menu.get(position);
item.setCount(i);
MainActivity.menu.set(position, item);
CharSequence text = menu.get(position).getName() +" : "+ menu.get(position).getCount();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
I found the cause of the problem. The both ArrayLists act like static (but they are not!). So I changed the decleration of the Item class, made count final. And that's it, problem is solved.
public class Item
{
private String name;
private final int count;
public Item(String s, int i) {
name = s;
count = i;
}
public String getName() {return name;}
public int getCount() {return count;}
public void setName(String s) {name = s;}
}

custom listview edit value

i have EditText in second activity.so the value enter here will be added to the custom listview in first activity.
i first activity in list i have textview,checkbox and button(edit). here textview will be from second activity edittext data. so here if i click on edit then it navigates to second activity of that particular data .am getting all these now .. in second acitity i want to edit the textfield value .so it has to display the edited value with this data in listview of particular row.
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
String cardNumberData=null;
}
public class Second extends Activity{
EditText cardNumber;
String cardNumberReceived;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.editcredit);
cardNumberReceived = getIntent().getStringExtra("cardwithoutstring");
System.out.println("cardWithOutStringReceived"+cardNumberReceived);
app = ((MyApplication) getApplicationContext());
cardNumber =(EditText)findViewById(R.id.cardnumber);
cardNumber.setText(cardNumberReceived);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.cardNumberData =cardNumber.getText().toString();
System.out.println("Gotcardname"+app.cardNumberData);
app.arryList.add(app.cardNumberData);
System.out.println("Array List Size "+app.arryList.size());
System.out.println("Array List Size "+app.cardTypeList.size());
Intent saveIntent =new Intent(Second.this,First.class);
startActivity(saveIntent);
}
});
}
}
public class First extends Activity{
protected ListItemsState[] mDeletedItemsStates;
protected ArrayAdapter<ListItemsState> mListAdapter;
protected ListView mFoldersListView;
protected Context mContext;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
mDeletedItemsStates = (ListItemsState[])getLastNonConfigurationInstance();
if (mDeletedItemsStates == null) {
mDeletedItemsStates = new ListItemsState[app.arryList.size()];
for (int i = 0; i < app.arryList.size(); i++) {
mDeletedItemsStates[i] = new ListItemsState(app.arryList.get(i),i);
}
}
ArrayList<ListItemsState> gridItemsList = new ArrayList<ListItemsState>();
gridItemsList.addAll(Arrays.asList(mDeletedItemsStates));
mListAdapter = new DeletedItemsStateArrayAdapter(this, gridItemsList);
mFoldersListView.setAdapter(mListAdapter);
mFoldersListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mFoldersListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "am thelist",
Toast.LENGTH_LONG).show();
}
});
}
private static class ListItemsState {
private String produ = "";
private boolean checked = false;
private int position;
public ListItemsState(String produ, int position) {
this.position = position;
}
public String getProdu() {
return produ;
}
public int getPosition() {
return position;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
/** Holds child views for one row. */
private static class ListItemsStateViewHolder {
private RadioButton checkBox;
private TextView produ;
private Button edit;
public TextView getProdu() {
return produ;
}
public Button getEdit() {
return edit;
}
public RadioButton getCheckBox() {
return checkBox;
}
}
private class DeletedItemsStateArrayAdapter extends
ArrayAdapter<ListItemsState> {
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private LayoutInflater inflater;
public DeletedItemsStateArrayAdapter(Context context,
List<ListItemsState> sentItemsStateList) {
super(context, R.layout.customlist, R.id.card,
sentItemsStateList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ListItemsState deletedItemsState = (ListItemsState) this
.getItem(position);
ListItemsStateViewHolder viewHolder = new ListItemsStateViewHolder();
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.customlist, null);
convertView.setTag(new ListItemsStateViewHolder());
}
else {
viewHolder = (ListItemsStateViewHolder) convertView.getTag();
viewHolder.checkBox = viewHolder.getCheckBox();
viewHolder.produ = viewHolder.getProdu();
viewHolder.edit = viewHolder.getEdit();
}
viewHolder.produ = (TextView) convertView.findViewById(R.id.card);
viewHolder.checkBox = (RadioButton) convertView.findViewById(R.id.radioButton1);
viewHolder.edit=(Button)convertView.findViewById(R.id.editbutton);
try {
viewHolder.checkBox.setTag(deletedItemsState);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
viewHolder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent edit =new Intent(getApplicationContext(), Second.class);
edit.putExtra("cardNumberSending",app.arryList.get(position));
edit.putExtra("Indexvalue",mFoldersListView.getItemIdAtPosition(position));
System.out.println("Index value ::::::::: "+mFoldersListView.getItemIdAtPosition(position));
startActivity(edit);
}
});
viewHolder.produ.setText(deletedItemsState.getProdu());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return mDeletedItemsStates;
}
}
You are adding the edited data to the ArrayList Again avoid it inside the Second Activity
app.cardNumberData = cardNumber.getText().toString();
if(arryList.indexOf(cardNumberReceived) != -1)
{
app.arryList.set(arryList.indexOf(cardNumberReceived), app.cardNumberData);
}else
{
app.arryList.add(app.cardNumberData);
}
In your second Activity do this onClick of save.

Categories

Resources