I have a problem in expandableListView that is weird with databinding.There is textview of quantity which can be incremented/decremented on button click.The Textview correctly updates at specific position. But when scrolled down the value changes the to textview at different position. Also , when group expanded value move the below item textview.Below are adapter , xml and model class.
public class ProductExpandableListAdapter extends BaseExpandableListAdapter {
private Activity contextActivity;
private ArrayList<ProductItems> productItemsArrayList;
public ProductExpandableListAdapter(ProductActivity productActivity, ArrayList<ProductItems> productItemsArrayList) {
this.contextActivity = productActivity;
this.productItemsArrayList = productItemsArrayList;
}
#Override
public void registerDataSetObserver(DataSetObserver dataSetObserver) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
}
#Override
public int getGroupCount() {
return this.productItemsArrayList.size();
}
#Override
public int getChildrenCount(int i) {
return 1;
}
#Override
public Object getGroup(int i) {
return this.productItemsArrayList.get(i);
}
#Override
public Object getChild(int i, int i1) {
return this.productItemsArrayList.get(i).getProductItemDescription();
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
final ProductItems productItems = productItemsArrayList.get(i);
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
final ProductItemBinding productItemsBinding = DataBindingUtil.inflate(layoutInflater, R.layout.product_items, viewGroup, false);
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productTitleTextView);
productItemsBinding.productTitleTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_64_pt));
view = productItemsBinding.getRoot();
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productPriceTextView);
productItemsBinding.productPriceTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_72_pt));
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.qtyTextView);
productItemsBinding.qtyTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_104_pt));
productItemsBinding.setHandler(new QuantityHandler() {
#Override
public void onQuantityIncrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.ADDITION);
Toast.makeText(contextActivity, "quantityIncrement : ", Toast.LENGTH_LONG).show();
}
#Override
public void onQuantityDecrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.SUBTRACTION);
Toast.makeText(contextActivity, "quantityDecrement : ", Toast.LENGTH_LONG).show();
}
});
productItemsBinding.setProductItems(productItems);
}
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
final ProductItemsChildBinding productItemsChildBinding = DataBindingUtil.inflate(layoutInflater, R.layout.product_items_child, viewGroup, false);
HelveticaNeueFontHelper.applyHelveticaneuelightFont(contextActivity, productItemsChildBinding.productDescriptionTextView);
productItemsChildBinding.productDescriptionTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_64_pt));
productItemsChildBinding.setProductItems(productItemsArrayList.get(i));
view = productItemsChildBinding.getRoot();
}
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public void onGroupExpanded(int i) {
}
#Override
public void onGroupCollapsed(int i) {
}
#Override
public long getCombinedChildId(long l, long l1) {
return 0;
}
#Override
public long getCombinedGroupId(long l) {
return 0;
}
private void changeQuantity(final ProductItemBinding productItemsBinding, ProductItems productItems, ObservableInt observableIntQty, String operand) {
switch (operand) {
case Constants.ADDITION:
if (observableIntQty.get() >= 0) {
observableIntQty.set(observableIntQty.get() + 1);
}
break;
case Constants.SUBTRACTION:
if (observableIntQty.get() > 0) {
observableIntQty.set(observableIntQty.get() - 1);
}
break;
}
contextActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
productItemsBinding.executePendingBindings();
}
});
}
}
<data class="ProductItemBinding">
<variable
name="productItems"
type="com.vtrio.waterapp.data.ProductItems" />
<variable
name="handler"
type="com.vtrio.waterapp.listeners.QuantityHandler" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#drawable/rounded_corner_bluegradient"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="#+id/productImageView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
app:imgSrc="#{productItems.productItemImage}" />
<LinearLayout
android:id="#+id/productInfoLinearLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="0.45"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/productTitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{productItems.productItemTitleName}" />
<TextView
android:id="#+id/productPriceTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{productItems.productItemPrice}" />
</LinearLayout>
<RelativeLayout
android:id="#+id/quantityModRelativeLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_weight="0.25"
android:gravity="center">
<Button
android:id="#+id/subtractQtyButton"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#color/addsubColor"
android:focusable="false"
android:focusableInTouchMode="false"
android:onClick="#{(v) -> handler.onQuantityDecrement()}"
android:text="#string/sub"
android:textColor="#color/addsubTextColor" />
<TextView
android:id="#+id/qtyTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#{Integer.toString(productItems.productItemQty)}" />
<Button
android:id="#+id/addQtyButton"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#color/addsubColor"
android:focusable="false"
android:focusableInTouchMode="false"
android:onClick="#{(v) -> handler.onQuantityIncrement()}"
android:text="#string/add"
android:textColor="#color/addsubTextColor" />
</RelativeLayout>
</LinearLayout> </layout>
ProductItems
public class ProductItems extends BaseObservable {
private String productItemTitleName;
private String productItemPrice;
private int productItemImage;
private String productItemDescription;
private ObservableInt productItemQty;
private ArrayList<ProductItems> cartItem;
public ProductItems(String productItemTitleName, String productItemPrice, int productItemImage, String productItemDescription, ObservableInt productItemQty) {
this.productItemTitleName = productItemTitleName;
this.productItemPrice = productItemPrice;
this.productItemImage = productItemImage;
this.productItemDescription = productItemDescription;
this.productItemQty = productItemQty;
}
public String getProductItemTitleName() {
return productItemTitleName;
}
public void setProductItemTitleName(String productItemTitleName) {
this.productItemTitleName = productItemTitleName;
}
public String getProductItemPrice() {
return productItemPrice;
}
public void setProductItemPrice(String productItemPrice) {
this.productItemPrice = productItemPrice;
}
public int getProductItemImage() {
return productItemImage;
}
public void setProductItemImage(int productItemImage) {
this.productItemImage = productItemImage;
}
public String getProductItemDescription() {
return productItemDescription;
}
public void setProductItemDescription(String productItemDescription) {
this.productItemDescription = productItemDescription;
}
#Bindable
public ObservableInt getProductItemQty() {
return productItemQty;
}
public void setProductItemQty(ObservableInt productItemQty) {
this.productItemQty = productItemQty;
notifyPropertyChanged(BR.productItemQty);
}
What is the problem and what can be done to solve this.
Maybe the problem is solved already but if not, I would change the getGroupView(...) method (and getChildView likewise) for the case when view is not null like this:
#Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
final ProductItems productItems = productItemsArrayList.get(i);
final ProductItemBinding productItemsBinding;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
productItemsBinding = DataBindingUtil.inflate(layoutInflater, R.layout.product_items, viewGroup, false);
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productTitleTextView);
productItemsBinding.productTitleTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_64_pt));
view = productItemsBinding.getRoot();
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.productPriceTextView);
productItemsBinding.productPriceTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_72_pt));
HelveticaNeueFontHelper.applyHelveticaneuemedFont(contextActivity, productItemsBinding.qtyTextView);
productItemsBinding.qtyTextView.setTextSize(contextActivity.getResources().getDimension(R.dimen.dim_104_pt));
}
else
{
productItemsBinding = (ProductItemBinding) view.getTag();
}
productItemsBinding.setHandler(new QuantityHandler() {
#Override
public void onQuantityIncrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.ADDITION);
Toast.makeText(contextActivity, "quantityIncrement : ", Toast.LENGTH_LONG).show();
}
#Override
public void onQuantityDecrement() {
changeQuantity(productItemsBinding, productItems, productItems.getProductItemQty(), Constants.SUBTRACTION);
Toast.makeText(contextActivity, "quantityDecrement : ", Toast.LENGTH_LONG).show();
}
});
productItemsBinding.setProductItems(productItems);
view.setTag(productItemsBinding);
return view;
}
Related
Hey I'm doing filtering data on my project using bottom Sheet with view-pager and two fragments i can pass data from activity to view-pager adapter and get in fragment through constructor but how can i get data from fragment to activity using bottom-sheet
this is how i send data from activity
adapter = new PagerAdapters(this.getSupportFragmentManager(),
tabLayout.getTabCount(),_id);
and receive data with constructor in fragment
public Filterfragment(String _id) {
this._id = _id;
}
And I'm using recyclerview to show data like this
So how can i send id of the item to activity so i can reload my recyclerview data when the apply button click.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_sheet"
android:background="#android:color/white"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabPadding="0dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_below="#id/tabs"
android:layout_above="#id/applyBtn"
android:layout_height="match_parent"
/>
<Button
android:id="#+id/applyBtn"
android:layout_width="match_parent"
android:text="Apply"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content" />
</RelativeLayout>
This is main recyclerview adapter
public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.FilterViewHolder> {
private static final String TAG = "FilterAdapter";
Context context;
List<TagTypeResult> tagTypeModels;
public static int current_pos = -1;
TagAdapter tagAdapter;
int rotationAngle = 0;
public FilterAdapter(Context context, List<TagTypeResult> tagTypeModels) {
this.context = context;
this.tagTypeModels = tagTypeModels;
}
#NonNull
#Override
public FilterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.filter_row_item,parent,false);
return new FilterAdapter.FilterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull FilterViewHolder filterViewHolder, int i) {
TagTypeResult tagTypeModel = tagTypeModels.get(i);
filterViewHolder.txt.setText(tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
if (tagTypeModel.getTagsLists() != null) {
if (tagTypeModel.getTagsLists().size() <= 0) {
filterViewHolder.arrow.setVisibility(View.GONE);
filterViewHolder.arrow.setRotationX(180);
} else {
filterViewHolder.arrow.setVisibility(View.VISIBLE);
filterViewHolder.arrow.setRotationX(0);
}
}else {
filterViewHolder.arrow.setVisibility(View.GONE);
}
tagAdapter = new TagAdapter(context, tagTypeModel.getTagsLists(), new TagInterface() {
#Override
public void tagClick(View view, int pos, String tagID) {
Log.d(TAG, "tagClick: "+tagID);
}
});
filterViewHolder.sub_list_recycler.setAdapter(tagAdapter);
tagAdapter.notifyDataSetChanged();
if (current_pos == filterViewHolder.getAdapterPosition()){
if (filterViewHolder.sub_list_recycler.getVisibility() == View.GONE) {
filterViewHolder.sub_list_recycler.setVisibility(View.VISIBLE);
}else {
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}else {
Log.i(TAG, "onBindViewHolder: sublist gone "+tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return tagTypeModels.size();
}
class FilterViewHolder extends RecyclerView.ViewHolder {
TextView txt;
ImageView arrow;
RecyclerView sub_list_recycler;
RelativeLayout linearLayout;
FilterViewHolder(#NonNull View itemView) {
super(itemView);
txt = itemView.findViewById(R.id.txt);
arrow = itemView.findViewById(R.id.arrow);
linearLayout = itemView.findViewById(R.id.main_cat_lay);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "onClick: "+current_pos);
if (current_pos != getAdapterPosition()) {
current_pos = getAdapterPosition();
notifyDataSetChanged();
}
else{
current_pos = -1;
notifyDataSetChanged();
}
}
});
sub_list_recycler = itemView.findViewById(R.id.sub_list_recycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
sub_list_recycler.setLayoutManager(mLayoutManager);
sub_list_recycler.addItemDecoration(new SimpleDividerItemDecoration(context));
}
}
}
sub recyclerView adapter :
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
private static final String TAG = "SublistAdapter";
Context context;
List<TagsList> tagsLists;
int pos = -1;
TagInterface tagInterface;
public TagAdapter(Context context, List<TagsList> tagsLists,TagInterface tagInterface) {
this.context = context;
this.tagsLists = tagsLists;
this.tagInterface = tagInterface;
}
#NonNull
#Override
public TagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tag_item,parent,false);
return new TagAdapter.TagViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TagViewHolder tagViewHolder, int i) {
TagsList tagsList = tagsLists.get(i);
tagViewHolder.tagtxt.setText(tagsList.getName());
if (tagsList.isChecked()){
tagViewHolder.tagName.setChecked(true);
}else {
tagViewHolder.tagName.setChecked(false);
}
}
#Override
public int getItemCount() {
return tagsLists.size();
}
public class TagViewHolder extends RecyclerView.ViewHolder {
TextView tagtxt;
CheckBox tagName;
RelativeLayout childClik;
public TagViewHolder(#NonNull View itemView) {
super(itemView);
//pri_txt = itemView.findViewById(R.id.pri_txt);
tagName = itemView.findViewById(R.id.tagName);
tagtxt = itemView.findViewById(R.id.tagtxt);
childClik = itemView.findViewById(R.id.childClik);
tagName.setEnabled(false);
childClik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = true;
if (isChecked)
{
tagsLists.get(getAdapterPosition()).setChecked(true);
tagName.setChecked(true);
tagInterface.tagClick(v,getAdapterPosition(),tagsLists.get(getAdapterPosition()).get_id());
Toast.makeText(context, "[pos]"+tagsLists.get(getAdapterPosition()).get_id(), Toast.LENGTH_SHORT).show();
}else
{
tagsLists.get(getAdapterPosition()).setChecked(false);
tagName.setChecked(false);
}
}
});
}
}
}
I'm parsing a JSON into a ExpandableListView, on each child the user can select the amount of each child he wants to have due +/- Buttons. The +/- Buttons are connected to a TextView where the total amount of each child gets displayed and the total cost will be displayed at the end of the line.
At the Bottom of the parent there should be a TextView with the summary of all the values calculated in every child of the ExpListView (Summary)
And the OK Button at the Bottom should send the amount of each child to the server (the amount is connected to a ID).
I'm having problems with reading out the amount of each child when I'm clicking on the "OK" Button - how can I build the bridge to the values of my Childs?
I also encounter problems reading out the cost of each childto calculate the total cost at the bottom. The onClickListener in the Child should somehow refresh the TextView at the bottom, but as far as I know, that's not going to be easy, right?
Has anyone an idea how to access the values?
This is the ChildView of my ListAdapter where the magic happens:
public class ExpandableListAdapterDrinks extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader,listDataHeaderPrice;
private HashMap<String,List<String>> listHashMap;
private List<Drink> drinksList;
class ViewHolder {
TextView childText,counterText, childUnitPrice, childFinalPrice;
Button btn_plus,btn_minus;
}
class DrinksListChildItem{
String name;
int quantity;
DrinksListChildItem(String name, int quantity){
this.name = name;
this.quantity = quantity;
}
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ExpandableListAdapterDrinks(Context context, List<Drink> drinksList) {
this.context = context;
this.drinksList= drinksList;
}
#Override
public int getGroupCount() {
return drinksList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return drinksList.get(groupPosition).getContent().size();
}
#Override
public Object getGroup(int groupPosition) {
return drinksList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return drinksList.get(groupPosition).getContent();
listHashMap.get(listDataHeader.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(final int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
String headerTitle = (String) drinksList.get(groupPosition).getTitle();
/** HEADER TEXT HERE */
if(view==null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_package_listgroup,null);
}
final LinearLayout bgcolor = view.findViewById(R.id.lblListHeaderLayout);
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
TextView lblListHeaderPrice = (TextView)view.findViewById(R.id.lblListHeader_Price);
Button lblListHeaderButton = view.findViewById(R.id.lblListHeaderButton);
lblListHeaderPrice.setVisibility(View.GONE);
lblListHeaderButton.setVisibility(View.GONE);
if(!drinksList.get(groupPosition).getBg().get(0).isEmpty() || !drinksList.get(groupPosition).getBg().get(1).isEmpty() ) {
List<String> colorGradientTopBottom = drinksList.get(groupPosition).getBg();
int[] colors = {Color.parseColor(colorGradientTopBottom.get(0)),Color.parseColor(colorGradientTopBottom.get(1))};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gd.setCornerRadius(0f);
bgcolor.setBackground(gd);
} else {
bgcolor.setBackgroundColor(ContextCompat.getColor(context, R.color.cardview_bg));
}
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
/** Drinks List */
final ViewHolder viewHolder;
final List<String> childDrink = drinksList.get(groupPosition).getContent();
final List<Integer> childPrice = drinksList.get(groupPosition).getPricelist();
//final String childText = childDrink.get(childPosition);
if(view == null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_drinks_listitem,null);
final TextView txtListChild = view.findViewById(R.id.lblListItemDrinks);
final TextView txtListDrinksUnitPrice = view.findViewById(R.id.lblListItemDrinksUnitPrice);
final TextView txtDrinksAmount = view.findViewById(R.id.vip_drinks_amount);
final TextView txtListDrinkPriceFinal = view.findViewById(R.id.lblListItemDrinksFinalPrice);
Button btn_plus = view.findViewById(R.id.vip_drinks_btn_plus);
Button btn_minus = view.findViewById(R.id.vip_drinks_btn_minus);
viewHolder = new ViewHolder();
viewHolder.childText = txtListChild;
viewHolder.childUnitPrice = txtListDrinksUnitPrice;
viewHolder.counterText = txtDrinksAmount;
viewHolder.childFinalPrice = txtListDrinkPriceFinal;
viewHolder.btn_plus = btn_plus;
viewHolder.btn_minus = btn_minus;
viewHolder.childText.setText(childDrink.get(childPosition));
viewHolder.counterText.setText("0");
viewHolder.childFinalPrice.setText("0");
final float headerPrice = childPrice.get(childPosition);
final int headerPriceInt = (int) headerPrice;
viewHolder.childUnitPrice.setText(String.format("%.02f",headerPrice).replace(".",",") +"€");
DrinksListChildItem child = childDrink.get(childPosition);
viewHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int t = Integer.parseInt(viewHolder.counterText.getText().toString());
ChildItem selectedItem = viewHolder.counterText.getText().toString();
selectedItem.quantity = selectedItem.quantity+1;
notifyDataSetChanged();
viewHolder.counterText.setText(String.valueOf(t + 1));
viewHolder.childFinalPrice.setText(String.valueOf((t+1)* headerPriceInt) + "€");
}
});
viewHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int t = Integer.parseInt(viewHolder.counterText.getText().toString());
DrinksListChildItem selectedItem = (DrinksListChildItem) getChild(pos.group,pos.child);
selectedItem.quantity = selectedItem.quantity-1;
notifyDataSetChanged();
viewHolder.counterText.setText(String.valueOf(t - 1));
viewHolder.counterText.setText(String.valueOf((t-1)* headerPriceInt) + "€");
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
return view;
I'm having massive problems glueing your code to my Code (expand problem with a TextView): I don't understand exactly how to connect the ChildItem child = childDrink.get(childPosition); to my drinksList to make the setOnCLickListener increase the selectedItem.quantity. The Code works somehow, but it messes up the order of my childs and it also selects the quantity in the other childs
Drinks (Pojo)
public class Drink {
#SerializedName("title")
#Expose
private String title;
#SerializedName("bg")
#Expose
private List<String> bg = null;
#SerializedName("content")
#Expose
private List<String> content = null;
#SerializedName("pricelist")
#Expose
private List<Integer> pricelist = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getBg() {
return bg;
}
public void setBg(List<String> bg) {
this.bg = bg;
}
public List<String> getContent() {
return content;
}
public void setContent(List<String> content) {
this.content = content;
}
public List<Integer> getPricelist() {
return pricelist;
}
public void setPricelist(List<Integer> pricelist) {
this.pricelist = pricelist;
}
}
VipDrinks(Pojo):
public class VipDrinks {
#SerializedName("drinks")
#Expose
private List<Drink> drinks = null;
public List<Drink> getDrinks() {
return drinks;
}
public void setDrinks(List<Drink> drinks) {
this.drinks = drinks;
}
}
JSON has the following structure:
{
"drinks":[ {
"title":,
"bg":[],
"content":[],
"pricelist":[],
},
{...}
]
}
Here is the Activity with the Parsing Request:
public class drinks_selection extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drinks_selection);
final ExpandableListView listView = findViewById(R.id.vip_drinks_listview);
/** PARSING JSON FROM SERVER */
final JsonObjectRequest galleryUrls = new JsonObjectRequest(Request.Method.GET, PARSE_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray packageArray = response.getJSONArray("drinks");
Log.e("response", String.valueOf(response));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Drink> vipDrinks = Arrays.asList(gson.fromJson(String.valueOf(packageArray),Drink[].class));
List<Drink> arrayList = new ArrayList<>(vipDrinks);
ExpandableListAdapterDrinks listAdapter = new ExpandableListAdapterDrinks(getApplicationContext(),arrayList);
listView.setAdapter( listAdapter);
listView.expandGroup(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERROR", String.valueOf(error));
}
});
RequestQueue rQ = Volley.newRequestQueue(this);
rQ.add(galleryUrls);
}
}
VIP Package List Group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/lblListHeaderLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/default_padding"
android:background="#drawable/bg_vip_booking"
android:orientation="horizontal"
>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingStart="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingEnd="#dimen/feed_item_padding_left_right"
android:layout_weight="0.9"
>
<TextView
android:id="#+id/lblListHeader"
android:textSize="#dimen/text_title_list_header"
android:textColor="#color/Textwhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_bold"
/>
<TextView
android:id="#+id/lblListHeader_Price"
android:textSize="#dimen/text_title_list_header"
android:textColor="#color/Textwhite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:fontFamily="#font/mont_bold"
/>
</RelativeLayout>
<Button
android:id="#+id/lblListHeaderButton"
android:layout_width="60dp"
android:layout_height="30dp"
android:background="#drawable/bg_btn_ripple_dark"
android:text="#string/btn_ok"
android:textColor="#color/Textwhite"
android:fontFamily="#font/mont_bold"
android:focusable="false"
/>
</LinearLayout>
VIP Drinks ListItem.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dip"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_centerInParent="true"
>
<TextView
android:id="#+id/lblListItemDrinks"
android:paddingTop="#dimen/padding_small"
android:paddingBottom="#dimen/padding_small"
android:textSize="#dimen/text_normal"
android:paddingLeft="#dimen/default_padding"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_medium"
android:textColor="#color/Textwhite"
app:layout_constraintStart_toStartOf="parent"
/>
<RelativeLayout
android:id="#+id/vip_drinks_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/lblListItemDrinks"
android:paddingStart="#dimen/default_padding"
android:layout_centerInParent="true"
android:paddingEnd="#dimen/default_padding"
app:layout_constraintEnd_toEndOf="parent"
>
<TextView
android:id="#+id/lblListItemDrinksUnitPrice"
android:textSize="#dimen/text_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_light"
android:textColor="#color/Textwhite"
android:paddingEnd="#dimen/padding_small"
/>
<Button
android:id="#+id/vip_drinks_btn_minus"
android:layout_toEndOf="#id/lblListItemDrinksUnitPrice"
android:layout_width="30dp"
android:layout_height="20dp"
android:text="-"
android:background="#drawable/bg_btn_ripple_dark"
android:textColor="#color/white"
android:textSize="14sp"
android:layout_marginEnd="#dimen/padding_small"
/>
<TextView
android:id="#+id/vip_drinks_amount"
android:layout_toEndOf="#+id/vip_drinks_btn_minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:fontFamily="#font/mont_light"
android:textSize="#dimen/text_normal"
android:layout_marginEnd="#dimen/padding_small"
/>
<Button
android:id="#+id/vip_drinks_btn_plus"
android:layout_toEndOf="#+id/vip_drinks_amount"
android:layout_width="30dp"
android:layout_height="20dp"
android:text="+"
android:background="#drawable/bg_btn_ripple_dark"
android:textColor="#color/white"
android:textSize="14sp"
android:layout_marginEnd="#dimen/padding_small"
/>
<TextView
android:id="#+id/lblListItemDrinksFinalPrice"
android:layout_toEndOf="#id/vip_drinks_btn_plus"
android:textSize="#dimen/text_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/mont_light"
android:textColor="#color/Textwhite"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Add a new class SelectedDrink like this:
public class SelectedDrink {
String content;
int qty;
}
Then try this adapter code:
public class ExpandableListAdapterDrinks extends BaseExpandableListAdapter {
private Context context;
private List<Drink> drinksList;
private Button btReset, btOk;
private List<Integer> groupSum;
private List<List<Integer>> qty;
private int totalSum = 0;
class ViewHolder {
TextView childText,counterText, childUnitPrice, childFinalPrice;
Button btn_plus,btn_minus;
}
class Pos{
int group;
int child;
Pos(int group, int child){
this.group = group;
this.child = child;
}
}
public ExpandableListAdapterDrinks(Context context, List<Drink> drinksList,
Button btReset, Button btOk) {
this.context = context;
this.drinksList= drinksList;
this.btReset = btReset;
this.btOk = btOk;
groupSum = new ArrayList<>();
qty = new ArrayList<>();
for(int i=0; i<drinksList.size(); i++) {
groupSum.add(0);
List<Integer> orderedQty = new ArrayList<>();
for(int j=0; j<drinksList.get(i).getContent().size(); j++) orderedQty.add(0);
qty.add(orderedQty);
}
}
private void resetGroupSum(int groupPosition) {
totalSum -= groupSum.get(groupPosition);
groupSum.set(groupPosition, 0);
resetGroupChildrenQty(groupPosition);
}
private void resetGroupChildrenQty(int groupPosition) {
for(int i=0; i<qty.get(groupPosition).size(); i++) qty.get(groupPosition).set(i, 0);
}
#Override
public int getGroupCount() {
return drinksList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return drinksList.get(groupPosition).getContent().size();
}
#Override
public Drink getGroup(int groupPosition) {
return drinksList.get(groupPosition);
}
#Override
public String getChild(int groupPosition, int childPosition) {
return drinksList.get(groupPosition).getContent().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
String headerTitle = drinksList.get(groupPosition).getTitle();
/** HEADER TEXT HERE */
if(view==null) {
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_package_listgroup,null);
}
LinearLayout bgcolor = view.findViewById(R.id.lblListHeaderLayout);
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
TextView lblListHeaderPrice = (TextView)view.findViewById(R.id.lblListHeader_Price);
Button lblListHeaderButton = view.findViewById(R.id.lblListHeaderButton);
if(groupSum.get(groupPosition) > 0){
lblListHeaderPrice.setVisibility(View.VISIBLE);
lblListHeaderPrice.setText(String.format("%.02f", (float)groupSum.get(groupPosition)).replace(".", ",") + "€");
}else{
lblListHeaderPrice.setVisibility(View.GONE);
lblListHeaderButton.setVisibility(View.GONE);
}
if(!drinksList.get(groupPosition).getBg().get(0).isEmpty() || !drinksList.get(groupPosition).getBg().get(1).isEmpty() ) {
List<String> colorGradientTopBottom = drinksList.get(groupPosition).getBg();
int[] colors = {Color.parseColor(colorGradientTopBottom.get(0)),Color.parseColor(colorGradientTopBottom.get(1))};
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
gd.setCornerRadius(0f);
bgcolor.setBackground(gd);
} else {
//bgcolor.setBackgroundColor(ContextCompat.getColor(context, R.color.cardview_bg));
}
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {
/** Drinks List */
ViewHolder viewHolder;
String childDrink = getChild(groupPosition, childPosition);
int childPrice = getGroup(groupPosition).getPricelist().get(childPosition);
if (view == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.vip_drinks_listitem, null);
viewHolder = new ViewHolder();
viewHolder.childText = view.findViewById(R.id.lblListItemDrinks);
viewHolder.childUnitPrice = view.findViewById(R.id.lblListItemDrinksUnitPrice);
viewHolder.counterText = view.findViewById(R.id.vip_drinks_amount);
viewHolder.childFinalPrice = view.findViewById(R.id.lblListItemDrinksFinalPrice);
viewHolder.btn_plus = view.findViewById(R.id.vip_drinks_btn_plus);
viewHolder.btn_minus = view.findViewById(R.id.vip_drinks_btn_minus);
viewHolder.btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int orderedQty = qty.get(pos.group).get(pos.child);
orderedQty++;
qty.get((pos.group)).set(pos.child, orderedQty);
groupSum.set(pos.group, groupSum.get(pos.group) + getGroup(pos.group).getPricelist().get(pos.child));
notifyDataSetChanged();
totalSum += getGroup(pos.group).getPricelist().get(pos.child);
btOk.setText(String.format("%.02f", (float)totalSum).replace(".", ",") + "€");
btReset.setEnabled(true);
}
});
viewHolder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pos pos = (Pos) v.getTag();
int orderedQty = qty.get(pos.group).get(pos.child);
if (orderedQty > 0) {
orderedQty--;
qty.get((pos.group)).set(pos.child, orderedQty);
groupSum.set(pos.group, groupSum.get(pos.group) - getGroup(pos.group).getPricelist().get(pos.child));
notifyDataSetChanged();
totalSum -= getGroup(pos.group).getPricelist().get(pos.child);
if (totalSum == 0) resetTotalSum();
else btOk.setText(String.format("%.02f", (float)totalSum).replace(".", ",") + "€");
}
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.childText.setText(childDrink);
viewHolder.childUnitPrice.setText(String.format("%.02f", (float)childPrice).replace(".", ",") + "€");
int orderedQty = qty.get(groupPosition).get(childPosition);
viewHolder.counterText.setText(String.valueOf(orderedQty));
viewHolder.childFinalPrice.setText(String.format("%.02f", (float)orderedQty*childPrice).replace(".", ",") + "€");
viewHolder.btn_minus.setTag(new Pos(groupPosition, childPosition));
viewHolder.btn_plus.setTag(new Pos(groupPosition, childPosition));
view.setTag(viewHolder);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return false;
}
public void resetTotalSum() {
for(int i=0; i<drinksList.size(); i++) {
resetGroupSum(i);
}
notifyDataSetChanged();
btReset.setEnabled(false);
btOk.setText(String.valueOf(0));
}
public ArrayList<SelectedDrink> getOrderList() {
ArrayList<SelectedDrink> orderList = new ArrayList<>();
for(int i=0; i<drinksList.size(); i++) {
for(int j=0; j<drinksList.get(i).getContent().size(); j++) {
if(qty.get(i).get(j) > 0) {
SelectedDrink selectedDrink = new SelectedDrink();
selectedDrink.content = getGroup(i).getContent().get(j);
selectedDrink.qty = qty.get(i).get(j);
orderList.add(selectedDrink);
}
}
}
return orderList;
}
}
I test the above with this activity:
public class MainActivity extends AppCompatActivity {
final private static int NUM_OF_GROUP = 5;
List<Drink> drinksList;
ExpandableListView listView;
ExpandableListAdapterDrinks expandableListAdapterDrinks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btRest = findViewById(R.id.btReset);
Button btOk = findViewById(R.id.btOK);
listView = findViewById(R.id.elvDrinks);
initDataList();
expandableListAdapterDrinks =
new ExpandableListAdapterDrinks(getApplicationContext(), drinksList, btRest, btOk);
listView.setAdapter(expandableListAdapterDrinks);
listView.expandGroup(0);
btRest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expandableListAdapterDrinks.resetTotalSum();
for(int i=0; i<drinksList.size(); i++) listView.collapseGroup(i);
listView.expandGroup(0);
}
});
btOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = "Nothing Selected";
Button button = (Button)view;
if(!button.getText().equals("0")) {
msg = "Upload!\n";
ArrayList<SelectedDrink> selectedDrinks = expandableListAdapterDrinks.getOrderList();
for(SelectedDrink selectedDrink: selectedDrinks) {
msg += selectedDrink.content + " " + selectedDrink.qty + "\n";
}
msg += "Total: " + button.getText();
}
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initDataList(){
drinksList = new ArrayList<>();
List<String> content;
List<Integer> pricelist;
List<String> bg;
for(int i=1; i<=NUM_OF_GROUP; i++) {
content = new ArrayList<>();
pricelist = new ArrayList<>();
bg = new ArrayList<>();
for(int j = 1; j<(NUM_OF_GROUP + new Random().nextInt(5)); j++){
content.add("Drink " + i + "-" + j);
pricelist.add(new Random().nextInt(1000));
bg.add("#008577");
bg.add("#D81B60");
}
Drink drink = new Drink();
drink.setTitle("Group " + i);
drink.setContent(content);
drink.setPricelist(pricelist);
drink.setBg(bg);
drinksList.add(drink);
}
}
}
and this layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/llBtns"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/btReset"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:enabled="false"
android:text="Reset" />
<Button
android:id="#+id/btOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="0" />
</LinearLayout>
<ExpandableListView
android:id="#+id/elvDrinks"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/llBtns">
</ExpandableListView>
</RelativeLayout>
Also, your Drink class, vip_package_listgroup.xml and vip_drinks_listitem.xml are also needed. Hope that helps!
I create app for sports site and need to make calendar events. There is a detail which I can't understand: how to make headers within Recyclerview for display of tournaments name that not to specified near each game (example "Примера" on the screen).
Is there a library or anyways for my task? I don’t want create many static Recyclerview and find agile ways.
Of course, there are a lot of tournaments in the calendar, so the headers should be the same.
Main class of the calendar:
public class FootballResults extends Fragment implements
View.OnClickListener, DatePickerDialog.OnDateSetListener{
private LinearLayoutManager linLM;
private FootballResultsAdapter adapter;
private ArrayList<FootballResultsData> dl;
String today_day;
String today_month;
String today_year;
String mDay;
String mMonth;
String mYear;
Button arrow_left;
Button arrow_right;
Button datepicker;
Switch swLive;
int n = 0;
//int n_plus = 1;
#SuppressLint("SetTextI18n")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rv = inflater.inflate(R.layout.results_football, container, false);
RecyclerView footballresults_feed1 = (RecyclerView) rv.findViewById(R.id.rcMatch1);
dl = new ArrayList<>();
footballresults_feed1.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new FootballResultsAdapter(getActivity(), dl);
footballresults_feed1.setAdapter(adapter);
arrow_left = (Button)rv.findViewById(R.id.arrow_left);
arrow_right = (Button)rv.findViewById(R.id.arrow_right);
datepicker = (Button)rv.findViewById(R.id.btnDatepick);
swLive = (Switch)rv.findViewById(R.id.swLive);
arrow_left.setOnClickListener(this);
arrow_right.setOnClickListener(this);
datepicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datepickermethod ();
}
});
swLive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {swLive.setText("");}
else {swLive.setText("");}
}
});
currenttime();
datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
ResultDisplay();
return rv;
}
private void ResultDisplay() {
#SuppressLint("StaticFieldLeak") AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... integers) {
ResultFeed ();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute();
}
void ResultFeed (){
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(C.RESULT_API+mYear+"/"+mMonth+"/"+mDay+"?sport_id=1")
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
JSONObject object = new JSONObject(response.body().string());
dl.clear();
JSONArray sports = object.getJSONArray("sports");
JSONObject tournament0 = sports.getJSONObject(0);
JSONArray tournament = tournament0.getJSONArray("tournaments");
for (int i=0; i<tournament.length(); i++){
JSONObject matches1 = tournament.getJSONObject(i);
Log.i (C.T, "Турнир: "+matches1.getString("tournament_name"));
JSONArray matches0 = matches1.getJSONArray("matches");
for (int j=0; j<matches0.length(); j++) {
JSONObject matches = matches0.getJSONObject(j);
String match_time = TimeFormat.TimeRadar(matches.getString("date_of_match")); //время начала матча
String match_res = matches.getString("ft_value");
String match_status = matches.getString("status");
if (match_res.equals("null")) {match_res = "-:-";}
if (match_status.equals("Не начался")) {match_status = "";}
if (match_status.equals("null")) {match_status = "";}
JSONObject team_home1 = matches.getJSONObject("team_home");
String team_home = team_home1.getString("short_name");
String team_home_logo = team_home1.getString("logo_small");
JSONObject team_away1 = matches.getJSONObject("team_away");
String team_away = team_away1.getString("short_name");
String team_away_logo = team_away1.getString("logo_small");
FootballResultsData data = new FootballResultsData(matches1.getString("tournament_name"),
match_time,
match_res,
team_home, team_away,
match_status,
team_home_logo,
team_away_logo);
dl.add(data);
}}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
#SuppressLint("SimpleDateFormat")
void currenttime () {
long date_today = System.currentTimeMillis();
today_day = new SimpleDateFormat("dd").format(date_today);
today_month = new SimpleDateFormat("MM").format(date_today);
today_year = new SimpleDateFormat("yyyy").format(date_today);
mDay = today_day; mMonth = today_month; mYear = today_year;
}
#SuppressLint("SimpleDateFormat")
void calendar (String dd, String mm, String yyyy, int day_n) {
String sourceDate = yyyy+"-"+mm+"-"+dd;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate;
try {
myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, day_n);
String mDate = new SimpleDateFormat("dd MM yyyy").format(new SimpleDateFormat("EEE MMM dd kk:mm:ss zzzz yyyy").parse(myDate.toString()));
mDay = new SimpleDateFormat("dd").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
mMonth = new SimpleDateFormat("MM").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
mYear = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("dd MM yyyy").parse(mDate));
Log.i(C.T, mDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
//currenttime ();
switch (v.getId()) {
case R.id.arrow_left: {n=n-1; break;}
case R.id.arrow_right: {n=n+1; break;}
default: break;
}
calendar(today_day, today_month, today_year, n);
datepicker.setText(Integer.parseInt(mDay)+" "+TimeFormat.monthDef(Integer.parseInt(mMonth))+" "+mYear);
ResultDisplay();
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
}
void datepickermethod () {
DatePickerDialog datepick = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
datepicker.setText(dayOfMonth+" "+TimeFormat.monthDef(month+1)+" "+year);
mDay = String.valueOf(dayOfMonth); mMonth = String.valueOf(month+1); mYear = String.valueOf(year);
n=0;
today_day = String.valueOf(dayOfMonth); today_month = String.valueOf(month+1); today_year = String.valueOf(year);
ResultDisplay();
}
}, Integer.parseInt(today_year), Integer.parseInt(today_month)-1, Integer.parseInt(today_day));
datepick.show();
}
}
For setters and getters:
class FootballResultsData {
public FootballResultsData(String tournament_name, String match_time, String match_result, String team_home, String team_away, String match_status, String team_home_logo, String team_away_logo) {
this.setTournament_name(tournament_name);
this.setMatch_time(match_time);
this.setMatch_result(match_result);
this.setTeam_home(team_home);
this.setTeam_away(team_away);
this.setMatch_status(match_status);
this.setTeam_home_logo(team_home_logo);
this.setTeam_away_logo(team_away_logo);
}
private String tournament_name;
private String match_time;
private String match_result;
private String team_home;
private String team_away;
private String match_status;
private String team_home_logo;
private String team_away_logo;
public String getMatch_time() { return match_time; }
public void setMatch_time(String match_time) {
this.match_time = match_time;
}
public String getTeam_home() {
return team_home;
}
public void setTeam_home(String team_home) {
this.team_home = team_home;
}
public String getTeam_away() {
return team_away;
}
public void setTeam_away(String team_away) {
this.team_away = team_away;
}
public String getMatch_status() {
return match_status;
}
public void setMatch_status(String match_status) {
this.match_status = match_status;
}
public String getMatch_result() { return match_result; }
public void setMatch_result(String match_result) { this.match_result = match_result; }
public String getTeam_home_logo() {
return team_home_logo;
}
public void setTeam_home_logo(String team_home_logo) {
this.team_home_logo = team_home_logo;
}
public String getTeam_away_logo() {
return team_away_logo;
}
public void setTeam_away_logo(String team_away_logo) {
this.team_away_logo = team_away_logo;
}
public String getTournament_name() {
return tournament_name;
}
public void setTournament_name(String tournament_name) {
this.tournament_name = tournament_name;
}
}
Cardview for a display of match:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tournament_result" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:background="#drawable/newsbody_file">
<TextView
android:id="#+id/linebelownews"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorNewsPressed" />
<TextView
android:id="#+id/match_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/linebelownews"
android:text="22:00" />
<TextView
android:id="#+id/match_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="ост." />
<TextView
android:id="#+id/match_res"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/match_time"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="2:2"
android:textStyle="bold" />
<TextView
android:id="#+id/match_th"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/match_time"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#+id/logo_th"
android:text="Динамо"
android:textAlignment="viewEnd"
android:textColor="#000000" />
<TextView
android:id="#+id/match_ta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_toEndOf="#+id/logo_ta"
android:layout_below="#id/match_time"
android:textColor="#000000"
android:text="Шахтер" />
<ImageView
android:id="#+id/logo_th"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_toStartOf="#id/match_res"
android:layout_below="#+id/match_time"
android:contentDescription="logo_th"
app:srcCompat="#drawable/author_file" />
<ImageView
android:id="#+id/logo_ta"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_below="#id/match_time"
app:srcCompat="#drawable/author_file"
android:layout_toEndOf="#id/match_res"
android:layout_marginBottom="5dp"
android:contentDescription="logo_th" />
<TextView
android:id="#+id/tournament_n"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/match_status"
android:layout_centerHorizontal="true"
android:text="#string/name_tournament" />
</RelativeLayout>
</android.support.v7.widget.CardView>
And main layout with Recyclerview:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tournament_result">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcMatch1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lCalendar">
<Button
android:id="#+id/arrow_left"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_toStartOf="#+id/btnDatepick"
android:background="#drawable/ic_arrow_left" />
<Button
android:id="#+id/arrow_right"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_toEndOf="#+id/btnDatepick"
android:background="#drawable/ic_arrow_right" />
<Button
android:id="#+id/btnDatepick"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Switch
android:id="#+id/swLive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="16dp" />
</RelativeLayout>
</RelativeLayout>
EDIT
Adapter:
class FootballResultsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ArrayList<FootballResultsData> footballresults_data = new ArrayList<FootballResultsData>();
private static int View_Header = 0;
private static int View_Item = 1;
public FootballResultsAdapter(Context context, ArrayList<FootballResultsData> footballresults_data) {
this.context = context;
this.footballresults_data = footballresults_data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if(viewType == View_Item) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_match, parent, false);
holder = new ViewHolder_item(view);
}
else if(viewType == View_Header) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_tournament, parent, false);
holder = new ViewHolder_header(view);
}
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
FootballResultsData NFD = footballresults_data.get(position);
if (holder instanceof ViewHolder_item) {
((ViewHolder_item) holder).match_time.setText(NFD.getMatch_time());
((ViewHolder_item) holder).match_result.setText(NFD.getMatch_result());
((ViewHolder_item) holder).team_home.setText(NFD.getTeam_home());
((ViewHolder_item) holder).team_away.setText(NFD.getTeam_away());
((ViewHolder_item) holder).match_status.setText(NFD.getMatch_status());
Glide.with(context).load(NFD.getTeam_home_logo()).into( ((ViewHolder_item) holder).team_home_logo);
Glide.with(context).load(NFD.getTeam_away_logo()).into( ((ViewHolder_item) holder).team_away_logo);
}
else if (holder instanceof ViewHolder_header) {
((ViewHolder_header) holder).tournament_name.setText(NFD.getTournament_name());
}
}
#Override
public int getItemViewType(int position) {
super.getItemViewType(position);
if(position == 0) {
return View_Header;
}else {
return View_Item;
}
}
#Override
public int getItemCount() {
return footballresults_data.size()+1;
}
public static class ViewHolder_item extends RecyclerView.ViewHolder {
public TextView match_time;
public TextView match_result;
public TextView team_home;
public TextView team_away;
public TextView match_status;
public ImageView team_home_logo;
public ImageView team_away_logo;
public ViewHolder_item(View itemView) {
super(itemView);
match_time = (TextView)itemView.findViewById(R.id.match_time);
match_result = (TextView)itemView.findViewById(R.id.match_res);
team_home = (TextView)itemView.findViewById(R.id.match_th);
team_away = (TextView)itemView.findViewById(R.id.match_ta);
match_status = (TextView)itemView.findViewById(R.id.match_status);
team_home_logo = (ImageView)itemView.findViewById(R.id.logo_th);
team_away_logo = (ImageView)itemView.findViewById(R.id.logo_ta);
}
}
public static class ViewHolder_header extends RecyclerView.ViewHolder {
public TextView tournament_name;
public ViewHolder_header(View itemView) {
super(itemView);
tournament_name = (TextView)itemView.findViewById(R.id.tournament_n);
}
}
}
Override getItemViewType (int position) return the appropriate type based on position and then inflate a different layout for header in onCreateViewHolder.
In Adapter
private static int View_Header =0;
private static int View_Item = 1;
Then
#Override
public int getItemViewType (int position) {
// position 0 return header type
if(position == 0) {
return View_Header;
}else {
return View_Item;
}
}
Then
// add 1 to the list
// total items is item in list + 1 for header
#Override
public int getItemCount() {
return footballresults_data.size()+1;
}
Then
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
if(viewType == View_Item) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_match, parent, false);
holder = new ViewHolder_Item(view);
}else if(viewType == View_Header) {
// inflate header layout
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.header_layout, parent, false);
holder = new ViewHolder_header(view);
}
return holder;
}
Then
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
// bind row items items
}
// create a separate viewholder class for header
else if( holder instanceof ViewHolder_header){
// bind header item
}
If you are looking for header and sub items (grouping items under a header) have a look at https://stackoverflow.com/a/42976078/653856. But the logic remains the same
I want to display UUID and Minor code of found beacons using listview in android.
I think I have problem with custom adapter.
Here is my actual code:
FoundBeacons.java
public class FoundBeacon extends Activity implements BeaconConsumer {
private BeaconManager beaconManager;
private ListView listview;
private ArrayList<Beacon> beaconList;
private AdapterBeacon bAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_beacon);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
beaconList = new ArrayList<Beacon>();
this.bAdapter = new AdapterBeacon(this, beaconList);
listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(bAdapter);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
bAdapter.copyBeacons(beacons);
listview.setAdapter(bAdapter);
}
});
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) {
}
}
}
AdapterBeacon.java
public class AdapterBeacon extends ArrayAdapter<Beacon> {
private Context context;
private ArrayList<Beacon> allBeacons;
private LayoutInflater mInflater;
private boolean mNotifyOnChange = true;
public AdapterBeacon(Context context, ArrayList<Beacon> mBeacons) {
super(context, R.layout.row_beacon);
this.context = context;
this.allBeacons = new ArrayList<Beacon>(mBeacons);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return allBeacons .size();
}
#Override
public Beacon getItem(int position) {
return allBeacons .get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getPosition(Beacon item) {
return allBeacons .indexOf(item);
}
#Override
public int getViewTypeCount() {
return 1; //Number of types + 1 !!!!!!!!
}
#Override
public int getItemViewType(int position) {
return 1;
}
public void copyBeacons(Collection<Beacon> beacons)
{
allBeacons.clear();
for (Beacon b : beacons)
{
allBeacons.add(b);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case 1:
convertView = mInflater.inflate(R.layout.row_beacon,parent, false);
holder.name = (TextView) convertView.findViewById(R.id.t1);
holder.description = (TextView) convertView.findViewById(R.id.t2);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(allBeacons.get(position).getId1().toString());
holder.description.setText(allBeacons.get(position).getId2().toString());
holder.pos = position;
return convertView;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mNotifyOnChange = true;
}
public void setNotifyOnChange(boolean notifyOnChange) {
mNotifyOnChange = notifyOnChange;
}
//---------------static views for each row-----------//
static class ViewHolder {
TextView name;
TextView description;
int pos; //to store the position of the item within the list
}
}
activity_found_beacon.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_found_beacon"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pio.pd_inz_ibeacon.FoundBeacon">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/listview" />
row_beacon.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"/>
<TextView
android:id="#+id/t2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"/>
<TextView
android:id="#+id/t3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"/>
Adapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private ExpandableListView mExpandableListView;
private List <Grupe> mGroupCollection;
private int[] groupStatus;
public ExpandableListAdapter() {}
public ExpandableListAdapter(Context pContext,
ExpandableListView pExpandableListView,
List <Grupe> pGroupCollection) {
mContext = pContext;
mGroupCollection = pGroupCollection;
mExpandableListView = pExpandableListView;
groupStatus = new int[mGroupCollection.size()];
setListEvent();
}
private void setListEvent() {
mExpandableListView
.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
groupStatus[arg0] = 1;
}
});
mExpandableListView
.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int arg0) {
groupStatus[arg0] = 0;
}
});
}
#Override
public String getChild(int arg0, int arg1) {
return mGroupCollection.get(arg0).getChildren().get(arg0).getPrimaoc_Poruke();
}
#Override
public long getChildId(int arg0, int arg1) {
return 0;
}
#Override
public View getChildView(int arg0, int arg1, boolean arg2, View arg3,
ViewGroup arg4) {
ChildHolder childHolder;
if (arg3 == null) {
arg3 = LayoutInflater.from(mContext).inflate(
R.layout.list_group_item, null);
childHolder = new ChildHolder();
childHolder.title = (TextView) arg3.findViewById(R.id.item_title);
arg3.setTag(childHolder);
} else {
childHolder = (ChildHolder) arg3.getTag();
}
childHolder.title.setText(mGroupCollection.get(arg0).getChildren().get(arg1).getPrimaoc_Poruke());
return arg3;
}
#Override
public int getChildrenCount(int arg0) {
return mGroupCollection.get(arg0).getChildren().size();
}
#Override
public Object getGroup(int arg0) {
return mGroupCollection.get(arg0);
}
#Override
public int getGroupCount() {
return mGroupCollection.size();
}
#Override
public long getGroupId(int arg0) {
return arg0;
}
#Override
public View getGroupView(int arg0, boolean arg1, View arg2, ViewGroup arg3) {
GroupHolder groupHolder;
if (arg2 == null) {
arg2 = LayoutInflater.from(mContext).inflate(R.layout.list_group, null);
groupHolder = new GroupHolder();
groupHolder.img = (ImageView) arg2.findViewById(R.id.tag_img);
groupHolder.title = (TextView) arg2.findViewById(R.id.group_title);
arg2.setTag(groupHolder);
} else {
groupHolder = (GroupHolder) arg2.getTag();
}
if (groupStatus[arg0] == 0) {
groupHolder.img.setImageResource(R.drawable.group_down);
} else {
groupHolder.img.setImageResource(R.drawable.group_up);
}
groupHolder.title.setText(mGroupCollection.get(arg0).getTip());
return arg2;
}
class GroupHolder {
ImageView img;
TextView title;
}
class ChildHolder {
TextView title;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
MainActivity
public class Glavna extends Activity implements OnClickListener, OnChildClickListener {
private List <Grupe> mGroupCollection;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavna);
prepareResource();
initPage();
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView1);
adapter = new ExpandableListAdapter(this,mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
private void prepareResource() {
mGroupCollection = new ArrayList <Grupe> ();
ge.setTip("Online korisnici");
mGroupCollection.add(ge);
AktivniChat gi = new AktivniChat(1, "receiver 1", new Korisnik(1, "sender1"));
mGroupCollection.get(0).setAktivniChat(gi);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
return true;
}
}
Set android:focusable="false" on all elements.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:paddingTop="5dip"
android:focusable="false">
<LinearLayout
android:id="#+id/groupItem"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#FFF385"
android:clickable="false"
android:focusable="false">
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF84"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="sample"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
Don't forget to enable child Selectable property..
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
It worked for me too... All items in layout (of the child) must be set to focusable="false" and clickable="false". But if you have buttons in child layout this will not work.