ExpandableListView OnChildClickListener doesn't work - java

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.

Related

How to build a viewpager with infinite scrolling without a JS library?

How can I give the viewpager a feature that will never run out and be scrolling indefinitely?
xml fragment_home:
<RelativeLayout
android:id="#+id/page_home_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:background="#fff"
tools:context=".Fragment.Home.HomeFragment">
<androidx.cardview.widget.CardView
android:id="#+id/card_viewpager"
android:elevation="0dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
app:cardCornerRadius="5dp">
<ir.develop.mhp.Action.CustomViewPager.ViewPagerCustomDuration
android:layout_width="match_parent"
android:layout_height="235dp"
android:id="#+id/slider_viewpager"
/>
</androidx.cardview.widget.CardView>
<com.tbuonomo.viewpagerdotsindicator.DotsIndicator
android:id="#+id/indicator"
android:layout_below="#id/card_viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:dotsColor="#C5C5C5"
app:dotsCornerRadius="8dp"
android:layout_margin="5dp"
app:dotsSize="7dp"
app:dotsSpacing="4dp"
android:layout_centerHorizontal="true"
android:layoutDirection="ltr"
app:dotsWidthFactor="2.5"
app:selectedDotColor="#color/colorPrimary"
app:progressMode="false"
/>
</RelativeLayout>
xml item_image_slider:
<ImageView android:layout_width="match_parent"
android:layout_height="235dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/image_slider"
android:layout_margin="10dp"
android:scaleType="fitXY"
android:src="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
java HomeFragment:
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_home, null);
cast(view);
setupSlider();
setupRecyclerView();
viewPager.setScrollDurationFactor(3);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == viewPager.SCROLL_STATE_IDLE){
userScrolled = false;
}else {
userScrolled = true;
}
}
});
viewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
}
});
return view;
}
private void cast(View view) {
viewPager = view.findViewById(R.id.slider_viewpager);
indicator = view.findViewById(R.id.indicator);
}
private void setupSlider() {
url = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Config.host + "getSlide.php", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("slide");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
url.add(jo.getString("slide"));
}
sliderAdapter = new SliderAdapter(getActivity(), url);
viewPager.setAdapter(sliderAdapter);
startAutoSlider(jsonArray.length());
indicator.setViewPager(viewPager);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
CustomToast.toastError(getActivity());
}
});
RequestVolley.get(getActivity()).add(jsonObjectRequest);
}
private void startAutoSlider(final int len) {
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (!userScrolled) {
if (viewPager.getCurrentItem() == len - 1) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
}
};
timer = new Timer(); // This will create a new Thread
timer.schedule(new TimerTask() { // task to be scheduled
#Override
public void run() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
java SliderAdapter:
public class SliderAdapter extends PagerAdapter {
private Context context;
private List<String> url;
public SliderAdapter(Context context, List<String> url) {
this.context = context;
this.url = url;
}
#Override
public int getCount() {
return url.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
View view = LayoutInflater.from(context).inflate(R.layout.item_image_slider , container , false);
ImageView imageView = view.findViewById(R.id.image_slider);
LoadImage.load(context , url.get(position) , imageView);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
It's very important not to use libraries.

ExpandableListView: Get input values from childs

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!

Android Databinding in ExpandableListView

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;
}

List View not calling onItemClickListener and OnItemLongClickListener

I have implemented an abstract class that has a List View like so:
public abstract class ExampleListFragment extends ExampleFragment{
protected ListView _listView;
public ExampleListFragment () {
super();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Set Up the Bottom Bar
View view = super.onCreateView(inflater, container, savedInstanceState);
addList();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public void addList() {
_listView = new ListView(getActivity());
RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
parms.addRule(RelativeLayout.CENTER_HORIZONTAL);
parms.addRule(RelativeLayout.BELOW, R.id.tableLayout);
_listView.setLayoutParams(parms);
_listView.setClickable(true);
_listView.setFocusable(true);
_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
longListClick(i);
return true;
}
});
_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listClick(i);
}
});
_layout.addView(_listView);
}
public abstract void longListClick(int pos);
public abstract void listClick(int pos);
}
I then have a class that inherits from this to implement the abstract methods which should be called when clicking an item in the list
public class TwitterFragment extends ExampleListFragment {
private TwitterAdapter _adapter;
//...
#Override
public void onSelected() {
_adapter = new TwitterAdapter(getActivity());
populateAdapter();
}
private void populateAdapter() {
showLoadingTweets();
new TwitterGetTimelineTask().execute(username); //fills adapter with Twitter status info...
}
#Override
public void longListClick(int pos) {
Toast toast = Toast.makeText(getActivity(),String.format("You have clicked item number: %d",pos),
Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void listClick(int pos) {
Toast toast = Toast.makeText(getActivity(),String.format("You have clicked item number: %d",pos),
Toast.LENGTH_SHORT);
toast.show();
}
//...
class TwitterGetTimelineTask extends AsyncTask<String, String, String> {
//...
}
}
However, whenever I click on an Item, it does not appear to even enter onItemClick functions.
Any ideas? help much appreciated.
*EDIT*
As requested, here is the code for my Adapter
public class TwitterAdapter extends BaseAdapter {
private ArrayList<StatusDetails> _statusDetailsArrayList;
private LayoutInflater _inflater;
public TwitterAdapter(Context context) {
_statusDetailsArrayList = new ArrayList<StatusDetails>();
_inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return _statusDetailsArrayList.size();
}
#Override
public Object getItem(int i) {
return _statusDetailsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return _statusDetailsArrayList.get(i).get_id();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = _inflater.inflate(R.layout.twitter_layout, null);
holder = new ViewHolder();
holder.img_icon = (ImageView) view.findViewById(R.id.statusImage);
holder.text_line1 = (TextView) view.findViewById(R.id.statusText);
holder.text_line2 = (TextView) view.findViewById(R.id.statusDateText);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Bitmap bmp = _statusDetailsArrayList.get(i).get_profile();
if (bmp == null) {
holder.img_icon.setImageResource(R.drawable.ic_action_twitter);
} else {
holder.img_icon.setImageBitmap(bmp);
}
holder.text_line1.setText(_statusDetailsArrayList.get(i).get_text());
holder.text_line2.setText(_statusDetailsArrayList.get(i).get_date());
return view;
}
public void addStatus(StatusDetails details) {
_statusDetailsArrayList.add(details);
}
public void setStatuses(ArrayList<StatusDetails> details) {
_statusDetailsArrayList = details;
}
public ArrayList<StatusDetails> getEvents() {
return _statusDetailsArrayList;
}
public void removeAll() {
_statusDetailsArrayList.clear();
}
private class ViewHolder {
ImageView img_icon;
TextView text_line1;
TextView text_line2;
}
}
And if needed, the XML of the layout of each list
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/statusImage"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Status"
android:id="#+id/statusText"
android:layout_alignParentTop="true"
android:autoLink="web"
android:textColor="#android:color/white"
android:layout_toRightOf="#+id/statusImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_below="#id/statusText"
android:text="Date"
android:id="#+id/statusDateText"
android:layout_alignBottom="#+id/statusImage"
android:layout_toRightOf="#+id/statusImage" />
Thanks.

How to give each node unique name

I want to display a tree having the individual name of its parent, second node, and its child nodes. I've coded by using Google help. This code display tree has all second and child nodes with the same names. How can I give an unique name to each node of a tree?
My Java code is:
package com.example.tree;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
ExpandableListView explvlist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
explvlist = (ExpandableListView)findViewById(R.id.ParentLevel);
explvlist.setAdapter(new ParentLevel());
}
public class ParentLevel extends BaseExpandableListAdapter
{
#Override
public Object getChild(int arg0, int arg1)
{
return arg1;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
CustExpListview SecondLevelexplv = new CustExpListview(MainActivity.this);
SecondLevelexplv.setAdapter(new SecondLevelAdapter());
SecondLevelexplv.setGroupIndicator(null);
return SecondLevelexplv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 4;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 1;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
TextView tv = new TextView(MainActivity.this);
tv.setText("Unit Testing");
tv.setBackgroundColor(Color.BLUE);
tv.setPadding(10, 7, 7, 7);
return tv;
}
#Override
public boolean hasStableIds()
{
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
}
public class CustExpListview extends ExpandableListView
{
int intGroupPosition, intChildPosition, intGroupid;
public CustExpListview(Context context)
{
super(context);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public class SecondLevelAdapter extends BaseExpandableListAdapter
{
#Override
public Object getChild(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
TextView tv = new TextView(MainActivity.this);
tv.setText("Campaign Page should not be null");
tv.setPadding(15, 5, 5, 5);
tv.setBackgroundColor(Color.RED);
tv.setLayoutParams(new ListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return tv;
}
#Override
public int getChildrenCount(int groupPosition)
{
return 2;
}
#Override
public Object getGroup(int groupPosition)
{
return groupPosition;
}
#Override
public int getGroupCount()
{
return 1;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
TextView tv = new TextView(MainActivity.this);
tv.setText("Get Campaign");
tv.setPadding(12, 7, 7, 7);
tv.setBackgroundColor(Color.CYAN);
return tv;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
}
I want each second and child nodes of tree to have an unique name and different colors.
Means you want to see the tree of data depending on the parent name.? So you used expandable list view.? right..?
Use these code..
main.xml having
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="HardCodedText" >
<ExpandableListView
android:id="#+id/expandableListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dip"
android:groupIndicator="#null"
android:scrollbars="none" >
</ExpandableListView>
</RelativeLayout>
And create the one ExpandListGroup.java file and add these code
public class ExpandListGroup {
private String Name;
private ArrayList<ExpandListChild> Items;
public ExpandListGroup(String name, ArrayList<ExpandListChild> items) {
super();
Name = name;
Items = items;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public ArrayList<ExpandListChild> getItems() {
return Items;
}
public void setItems(ArrayList<ExpandListChild> items) {
Items = items;
}
}
Add the another one ExpandListChild.java file for child
public class ExpandListChild {
private String Name;
private String Tag;
public ExpandListChild(String name, String tag) {
super();
Name = name;
Tag = tag;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getTag() {
return Tag;
}
public void setTag(String tag) {
Tag = tag;
}
}
And add these code in your MainActivity.java
public class ConfigureMyOrderItem extends MainActivity {
private ArrayList<ExpandableConfigureGroup> group_list;
private ArrayList<ExpandableConfigureChild> child_list;
ExpandableListView mExpandableListView;
ConfigureMyOrderAdapter adapter;
Button btn_confirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configure_my_order_item);
initView();
}
public void initView() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListViewConfigure);
btn_confirm = (Button) findViewById(R.id.btn_Confirm_order);
btn_confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ConfigureMyOrderItem.this,
MyOrderActivity.class);
startActivity(intent);
}
});
group_list = SetStandardGroups();
adapter = new ConfigureMyOrderAdapter(ConfigureMyOrderItem.this,
mExpandableListView, group_list);
mExpandableListView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater()
.inflate(R.menu.activity_configure_my_order_item, menu);
return true;
}
public ArrayList<ExpandableConfigureGroup> SetStandardGroups() {
group_list = new ArrayList<ExpandableConfigureGroup>();
child_list = new ArrayList<ExpandableConfigureChild>();
group_list.add(new ExpandableConfigureGroup("Group", child_list));
child_list.add(new ExpandableConfigureChild("Child1"));
child_list.add(new ExpandableConfigureChild("Child2"));
child_list.add(new ExpandableConfigureChild("Child3"));
child_list.add(new ExpandableConfigureChild("Child4"));
child_list = new ArrayList<ExpandableConfigureChild>();
group_list.add(new ExpandableConfigureGroup("Category",
child_list));
child_list.add(new ExpandableConfigureChild("Item1"));
child_list.add(new ExpandableConfigureChild("Item2"));
child_list.add(new ExpandableConfigureChild("Item3"));
child_list.add(new ExpandableConfigureChild("Item4"));
}
public void HomeButton(View v) {
startActivity(new Intent(v.getContext(), MainActivity.class));
}
#Override
public void onClickQuickView(View v) {
// TODO Auto-generated method stub
super.onClickQuickView(v);
}
#Override
public void onClickQuickViewStatus(View v) {
// TODO Auto-generated method stub
super.onClickQuickViewStatus(v);
}
}
Also create the ConfigureMyOrderAdapter.java file
public class ConfigureMyOrderAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<ExpandableConfigureGroup> groups;
private ExpandableListView mExpandableListView;
private int[] groupStatus;
public ConfigureMyOrderAdapter(Context context,
ExpandableListView mExpandableListView,
ArrayList<ExpandableConfigureGroup> groups) {
this.context = context;
this.groups = groups;
this.mExpandableListView = mExpandableListView;
groupStatus = new int[groups.size()];
setListEvent();
}
private void setListEvent() {
mExpandableListView
.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
// TODO Auto-generated method stub
groupStatus[arg0] = 1;
}
});
mExpandableListView
.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int arg0) {
// TODO Auto-generated method stub
groupStatus[arg0] = 0;
}
});
}
public void addItem(ExpandableConfigureChild item,
ExpandableConfigureGroup group) {
if (!groups.contains(group)) {
groups.add(group);
}
int index = groups.indexOf(group);
ArrayList<ExpandableConfigureChild> ch = groups.get(index).getItems();
ch.add(item);
groups.get(index).setItems(ch);
}
public Object getChild(int groupPosition, int childPosition) {
ArrayList<ExpandableConfigureChild> chList = groups.get(groupPosition)
.getItems();
return chList.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean arg2, View view, ViewGroup arg4) {
ExpandableConfigureChild child = (ExpandableConfigureChild) getChild(
groupPosition, childPosition);
if (view == null) {
#SuppressWarnings("static-access")
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = infalInflater.inflate(
R.layout.configure_list_raw_group_item, null);
}
TextView tv_price = (TextView) view.findViewById(R.id.item_price);
tv_price.setText(child.getTag().toString());
tv_price.setTag(child.getTag());
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<ExpandableConfigureChild> chList = groups.get(groupPosition)
.getItems();
return chList.size();
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#SuppressWarnings("static-access")
#Override
public View getGroupView(int groupPosition, boolean arg1, View view,
ViewGroup arg3) {
ExpandableConfigureGroup group = (ExpandableConfigureGroup) getGroup(groupPosition);
if (view == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inf.inflate(R.layout.configure_list_raw_group, null);
}
TextView tv = (TextView) view.findViewById(R.id.txtRestaurantMenuName);
tv.setText(group.getName());
ImageView img = (ImageView) view.findViewById(R.id.img_rightarrow);
if (groupStatus[groupPosition] == 0) {
img.setImageResource(R.drawable.navigation_next);
} else {
img.setImageResource(R.drawable.navigation_expandable);
}
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
and also create the two xml for the custom configure_list_raw_group.xml layout. so it is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="45dip"
android:orientation="horizontal"
android:weightSum="100"
tools:ignore="HardCodedText" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="45dip"
android:layout_marginLeft="4dip"
android:layout_weight="88"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/txtRestaurantMenuName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RestaurantMenu Name"
android:textSize="14sp" />
</LinearLayout>
<ImageView
android:id="#+id/img_rightarrow"
android:layout_width="0dip"
android:layout_height="45dip"
android:layout_gravity="center_vertical"
android:layout_weight="7"
android:contentDescription="#string/hello_world"
android:src="#drawable/navigation_next_item" />
</LinearLayout>
and second for the child of group configure_list_raw_group_item.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/groupItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:orientation="horizontal"
android:weightSum="100"
tools:ignore="HardCodedText" >
<TextView
android:id="#+id/item_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_weight="75"
android:text="sample"
android:textSize="12sp" />
</LinearLayout>

Categories