I am using InqBarna's library for showing data in table format. I am facing issue for sort button change (ascending and descending order) when clicked on sort button on table header. Please help.
Here code snippet.
private View getHeader(int row, int column, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = activity.getLayoutInflater().inflate(R.layout.item_table_header, parent, false);
}
convertView.setBackgroundResource(column % 2 == 0 ? R.color.header_dark_gray : R.color.header_light_gray);
((TextView) convertView.findViewById(android.R.id.text1)).setText(headers[column + 1]);
imageButtons[column +1] = ((ImageButton) convertView.findViewById(R.id.sortButton));
imageButtons[column +1].setTag(headers[column + 1]);
imageButtons[column +1].setOnClickListener(onClickListener);
return convertView;
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageButton imageButton =(ImageButton)v.findViewWithTag(v.getTag());
String header = v.getTag().toString();
switch (header) {
// logic for change image
case Query.AQ_NO:
if (AQ_NO_FLAG) {
imageButton.setImageResource(R.drawable.sort_asc);
}
break;
}
}
It could help you.
This is a wrapper for InqBarna's library.
This is a code snippet of how to achieve the sorting headers. Anyway you will have to see the whole example to understand how it works.
Here you render the header view:
public class OriginalHeaderCellViewGroup extends FrameLayout
implements
TableFixHeaderAdapter.HeaderBinder<ItemSortable> {
private Context context;
public TextView textView;
public ImageView iv_order_asc, iv_order_desc;
public OriginalHeaderCellViewGroup(Context context) {
super(context);
this.context = context;
init();
}
private void init() {
LayoutInflater.from(context).inflate(R.layout.text_sotable_view_group, this, true);
textView = (TextView) findViewById(R.id.tv_text);
iv_order_asc = (ImageView) findViewById(R.id.iv_order_asc);
iv_order_desc = (ImageView) findViewById(R.id.iv_order_desc);
}
#Override
public void bindHeader(ItemSortable item, int column) {
textView.setText(item.text.toUpperCase());
drawOrderArrows(item.order);
}
private void drawOrderArrows(int order) {
iv_order_desc.setImageResource(order == -1 ? R.drawable.ic_arrow_drop_up_24dp : R.drawable.ic_arrow_drop_up_24dp_disabled);
iv_order_asc.setImageResource(order == 1 ? R.drawable.ic_arrow_drop_down_24dp : R.drawable.ic_arrow_drop_down_24dp_disabled);
}
and here you attach the listener to the table adapter and perform the sorting:
private void setListeners(final OriginalSortableTableFixHeaderAdapter adapter) {
TableFixHeaderAdapter.ClickListener<ItemSortable, OriginalHeaderCellViewGroup> clickListenerHeader = new TableFixHeaderAdapter.ClickListener<ItemSortable, OriginalHeaderCellViewGroup>() {
#Override
public void onClickItem(ItemSortable item, OriginalHeaderCellViewGroup viewGroup, int row, int column) {
updateOderIndicators(item, column, adapter);
boolean orderAsc = item.order == 1;
boolean orderSectionsAsc =firstHeader.orderSectionsAsc;
applyOrder(orderAsc, orderSectionsAsc, column, adapter);
}
};
adapter.setClickListenerHeader(clickListenerHeader);
}
private void updateOderIndicators(ItemSortable item, final int column, TableFixHeaderAdapter adapter) {
final boolean orderAsc = item.order == 1;
firstHeader.order = 0;
for (ItemSortable itemAux : header) itemAux.order = 0;
item.order = !orderAsc ? 1 : -1;
}
private void applyOrder(final boolean orderAsc, final boolean orderSectionsAsc, final int column, TableFixHeaderAdapter adapter) {
Collections.sort(body, new Comparator<NexusWithImage>() {
#Override
public int compare(NexusWithImage nexus1, NexusWithImage nexus2) {
if (nexus1.isSection() || nexus2.isSection()) return 1;
else if (orderAsc)
return nexus1.data[column + 1].compareToIgnoreCase(nexus2.data[column + 1]);
else
return nexus2.data[column + 1].compareToIgnoreCase(nexus1.data[column + 1]);
}
});
adapter.setBody(body);
}
Hope it helps you.
Related
I have a listview and a button in my main activity and three layout ressource files (right.xml, mid.xml and left.xml [They're relative layout]).
I want to make an arrayList (with strings and drawable (images)) and each time I push the button in main.xml the first content of the arrayList will appear at the bottom of the screen (either left, mid or right --> depend of the order of the arrayList) and when I click again the next item (string or drawable) will appear beneath it, pushing it in an upward motion.
UPDATE
I made a Model and an Adapter
Here is the model
public class ModelC1 {
public String C1Name;
public String C1Text;
public int id;
public boolean isSend;
public ModelC1(String C1Name, String C1Text, int id, boolean isSend){
this.id = id;
this.C1Name = C1Name;
this.C1Text = C1Text;
this.isSend = isSend;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getC1Name() {
return C1Name;
}
public void setC1Name(String C1Name){
this.C1Name = C1Name;
}
public String getC1Text() {
return C1Text;
}
public void setC1Text (String C1Text){
this.C1Text = C1Text ;
}
public boolean isSend() {
return isSend;
}
public void setIsSend(boolean send){
isSend = send;
}
Here is the Adapter
public class AdapterC1 extends BaseAdapter {
private List<ModelC1> listChat;
private LayoutInflater inflater;
private Context context;
public AdapterC1(List<ModelC1> listChat, Context context){
this.listChat = listChat;
this.context = context;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listChat.size();
}
#Override
public Object getItem(int i) {
return listChat.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View vi = convertView;
if(convertView == null ){
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}else{
if(listChat.get(i).isSend() == 0)
vi=inflater.inflate(R.layout.list_send,null);
else if ((listChat.get(i).isSend() == 1))
vi=inflater.inflate(R.layout.list_recv,null);
else if ((listChat.get(i).isSend() == 2))
vi=inflater.inflate(R.layout.list_mid,null);
}
if(listChat.get(i).isSend() !=0 || listChat.get(i).isSend() !=1 || listChat.get(i).isSend() !=2 ){
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
if(bubbleTextView != null)
bubbleTextView.setText(listChat.get(i).C1Text);
TextView nameTextView = (TextView) vi.findViewById(R.id.nameChat);
if(nameTextView != null)
nameTextView.setText(listChat.get(i).C1Name);
}else{
vi=inflater.inflate(R.layout.list_mid,null);
BubbleTextView bubbleTextView = (BubbleTextView) vi.findViewById(R.id.bubbleChat);
bubbleTextView.setText("THE END");
}
return vi;
}
And here is the activity
public class Chat1 extends AppCompatActivity {
private static final String TAG = "Chat1";
private AdapterC1 adapter;
private List<ModelC1> listChat = new ArrayList<>();
private int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
RecyclerView chatContent1 = findViewById(R.id.chatContent1);
}
private ModelC1 setUpMessage(){
Log.d(TAG, "setUpMessage: Exec");
return();
}
///OnClick of the button in the activity_chat1.xml
public void nextClicked1(View view) {
Log.d(TAG, "nextClicked: Is Clicked");
///After the limit of the arraylist is reached
final int limit = 40;
if(count == limit){
Log.d(TAG, "nextClicked: Limit Reached");
Intent i = new Intent(Chat1.this, MainActivity.class);
startActivity(i);
}else{
///Call the list
loadList(null);
}
}
///Load the list of arrays?
public void loadList(View view){
ModelC1 chat = setUpMessage();
listChat.add(chat);
///The ID of the recycleview in the activity_chat1.xml
final RecyclerView recyclerview = findViewById(R.id.chatContent1);
///The adapter
final AdapterC1 adapter = new AdapterC1(listChat, this);
///Make the recyclerview always scroll
///the adapter
///recyclerview.setAdapter(adapter);
}
My questions are now how do I make the ArrayList (containing strings and drawables) and how to link the ArrayList to make it appear one by one when I click on the button ?
As for the ArrayList, will soemthing like that works ?
private List<List<String>> textChat1 = new ArrayList<List<String>>();
ArrayList<String> textChat1 = new ArrayList<String>();
textChat1.add("This is message 1");
textChat1.add("This is message 2");
textChat1.add("This is message 2");
addresses.add(textChat1);
How can I add images and how to say which strings inflate which layout (left, mid or right) ?
You can do your job like this: in your Adapter's getView method ,
#Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
if (position == 1) {
convertView = getLayoutInflater().inflate(R.layout.left, container, false);
} else if (position == 2) {
convertView = getLayoutInflater().inflate(R.layout.mid, container, false);
} else {
convertView = getLayoutInflater().inflate(R.layout.right, container, false);
}
}
//your code here
return convertView;
}
This will do your job, but, I suggest you to use Recyclerview because it's more efficient and better in terms of looks as well as memory management.
I am trying to make an application with a ListView that include a Country Flag and name. This is so that the user can click on them and be shown images of the country that they wouldve taken before. However for about 3 seconds when the listview loads if i try to scroll it will sort of glitch and send me back to top. This is the code..
public class CountriesListAdapter extends ArrayAdapter {
private int resource;
private LayoutInflater inflater;
private List<CountryModel> countryModels;
private WeakReference<TextView> selectedCountryIdtxt;
private boolean useFilter;
private WeakReference<ProgressBar> progressBarWeakReference;
public int getSelectedCountryId() {
return selectedCountryId;
}
public void setSelectedCountryId(int selectedCountryId) {
this.selectedCountryId = selectedCountryId;
}
private int selectedCountryId;
public CountriesListAdapter(#NonNull WeakReference<Context> context, int resourceId, WeakReference<TextView> textView, #NonNull List<CountryModel> countryModelList, boolean useFilter, WeakReference<ProgressBar> progressBarWeakReference){
super(context.get(), resourceId, countryModelList);
selectedCountryIdtxt = textView;
resource = resourceId; //the id of the template file
inflater = LayoutInflater.from(context.get());
this.countryModels = countryModelList;
selectedCountryId = -1;
this.useFilter = useFilter;
this.progressBarWeakReference = progressBarWeakReference;
}
public int getCount() {
if (countryModels != null)
return countryModels.size();
return 0;
}
public CountryModel getItem(int position) {
if (countryModels != null)
return countryModels.get(position);
return null;
}
public long getItemId(int position) {
if (countryModels != null)
return countryModels.get(position).hashCode();
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// this method is automatically called for every object in our list
//basically it's called for every single row before it is generated
// this method is called per row
convertView = (ConstraintLayout) inflater.inflate(resource, null);
//the variable countryModel is fiiled with current object that is being processed
final CountryModel countryModel = countryModels.get(position);
TextView countryName = convertView.findViewById(R.id.countryNamelbl);
final ImageView countryFlag = convertView.findViewById(R.id.countryFlagimg);
final ImageView checked = convertView.findViewById(R.id.countryCheckedimg);
//this is done for every object in the list
assert countryModel != null;
countryName.setText(countryModel.getName());
Picasso.get().load(countryModel.getImage()).fit().into(countryFlag);
if(!useFilter) {
if (selectedCountryId == countryModel.getId()) {
checked.setVisibility(View.VISIBLE);
} else {
checked.setVisibility(View.INVISIBLE);
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!useFilter) {
if (checked.getVisibility() == View.VISIBLE) {
checked.setVisibility(View.INVISIBLE);
selectedCountryId = -1;
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
} else {
if (selectedCountryId == -1) {
checked.setVisibility(View.VISIBLE);
selectedCountryId = countryModel.getId();
} else {
selectedCountryId = countryModel.getId();
notifyDataSetChanged();
}
selectedCountryIdtxt.get().setText(String.valueOf(selectedCountryId));
}
} else {
Intent i = new Intent(getContext(), PicturesActivity.class);
i.putExtra("countryId",countryModel.getId());
i.putExtra("countryName", countryModel.getName());
getContext().startActivity(i);
}
}
});
progressBarWeakReference.get().setVisibility(View.INVISIBLE);
return convertView;
}
public List<CountryModel> getCountryModels() {
return countryModels;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.countryModels = countryModels;
}
}
The problem was actually in another class, i was calling the adapter for every list item instead of just once... oops.
Thanks for the replies though!
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
I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});
I am using a baseadapter for my customize spinner with checkbox that allow the user to choose multiple values. I have an update button in my application, and I need to set the values from the database as true in the checkbox. My problem is I don't know how to do it. For example I have ["A","B","C","D"] values in my spinner, in my database I got B and D. How will i automatically check that values when I open the activity.
Here is my code that populate my customize spinner
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
here is my ConsumerSegmentListAdapter. The listview acts as my spinner.
public class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.DropDownList.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.DropDownList.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mListCustomerSegment.get(position));
final int position1 = position;
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setText(position1);
}
});
if(S_10th_IReportMain.checkSelectedConsumerSegment[position])
holder.chkbox.setChecked(true);
else
holder.chkbox.setChecked(false);
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position1){
if (!S_10th_IReportMain.checkSelectedConsumerSegment[position1]) {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = true;
selectedCount++;
} else {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = false;
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
I think You need to manage another storage for selected / unselected items and move it to the adapter. E.g. it can be HashSet<String>. Then code would look the following (note, that I made it compilable, because it's impossible to compile one provided in the question):
public class S_10th_IReportMain extends Activity {
boolean expandedConsumerSegment;
ConsumerSegmentListAdapter mAdapter;
private static class DatabaseHandler {
List<String> setItemOnConsumerSeg() {
return Collections.emptyList();
}
}
private static class BrandListAdapter {
static String getSelected() {
return "string";
}
}
DatabaseHandler databaseHandler = new DatabaseHandler();
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
final TextView tv_ConsumerSegment = (TextView) findViewById(R.id.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (String segment : consumerSegments) {
if (mAdapter.isChecked(segment)) {
selected += segment;
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.id.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
PopupWindow pwConsumerSegment;
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.id.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
public static class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
private HashSet<String> mCheckedItems;
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
/**
* Should be called then new data obtained from DB
*
* #param checkedItems array of strings obtained from DB
*/
public void setCheckedItems(final String[] checkedItems) {
mCheckedItems.clear();
Collections.addAll(mCheckedItems, checkedItems);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String text = mListCustomerSegment.get(position);
final boolean checked = isChecked(text);
holder.tv.setText(mListCustomerSegment.get(position));
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText(position, checked, text);
}
});
if(checked) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position, boolean checked, String text){
if (!checked) {
mCheckedItems.add(text);
selectedCount++;
} else {
mCheckedItems.remove(text);
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
/**
* #param segment to be checked
*
* #return true if the segment is checked
*/
public boolean isChecked(final String segment) {
return mCheckedItems.contains(segment);
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
}
So, then You obtain new data from database which should be checked You can just call mAdapter.setCheckedItems().
I already make it. By this:
for (int j=0; j<brands.size(); j++)
{
for(String chosenElement : Brands)
{
int index = brands.indexOf(chosenElement);
checkSelected[index] = true;
}
}
What I did is i look for the index of my chosen arraylist to my spinner's adapter and set the the checkbox index into true. That simple. Anyway thanks for the idea.