I am using ExpandableListView in an Activity. I have a TextView and a CheckBox in the GroupView . When I click the CheckBox the corresponding list item expands or collapses depending upon its state. I don't want to change the state of a list item on clicking the CheckBox in the GroupView. How can I achieve this?
This is my layout :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ExpandableListView
android:id="#+id/expandableListView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomPanel"
android:dividerHeight="0.5dp"
android:drawSelectorOnTop="false"
android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorRight" />
<LinearLayout
android:id="#+id/bottomPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:id="#+id/bt_delete_group"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/delete_group" />
<Button
android:id="#+id/bt_add_group"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/add_group" />
<Button
android:id="#+id/bt_show_select"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/show_select" />
</LinearLayout>
</RelativeLayout>
</FrameLayout>
And this is my adapter :
This is my Adapter after edit :
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<RowBean>> expandableListDetail;
public static ArrayList<Integer> selected = new ArrayList<>();
private Realm realm = Realm.getDefaultInstance();
public CustomExpandableListAdapter(Context context, List<String> expandableListTitle,
HashMap<String, List<RowBean>> expandableListDetail) {
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
}
#Override
public Object getChild(int listPosition, int expandedListPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)).get(expandedListPosition);
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(int listPosition, final int expandedListPosition, boolean isLastChild, View convertView, ViewGroup parent) {
// for(RowBean r : expandableListDetail.get(expandableListTitle.get(listPosition))){
// Log.e("is select " , r.getTitle() + " " +r.isSelected() + " , " + listPosition + " ," +expandedListPosition);
// }
RowBean rowBean = (RowBean) getChild(listPosition, expandedListPosition);
RowBean rowBean1 = expandableListDetail.get(expandableListTitle.get(listPosition)).get(expandedListPosition);
// Log.e("rowbean " , rowBean1.getTitle() + " , " + rowBean1.isSelected() );
final String expandedListText = rowBean.getTitle();
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.list_item_holder, null);
}
TextView expandedListTextView = (TextView) convertView.findViewById(R.id.expandedListItem);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.expandedListItemCheckbox);
expandedListTextView.setText(expandedListText);
checkBox.setChecked(rowBean.isSelected());
return convertView;
}
#Override
public int getChildrenCount(int listPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition)).size();
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(final int listPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final ViewGroup groupview = parent;
SharedPreferences pref = context.getSharedPreferences("MAIN_PREF", MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
final String listTitle = (String) getGroup(listPosition);
boolean[] sel = {RealmController.getGroup(listTitle, realm).isSelect()};
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// convertView = layoutInflater.inflate(R.layout.list_group, null);
convertView = layoutInflater.inflate(R.layout.holder_layout, null);
}
// TextView listTitleTextView = (TextView) convertView
// .findViewById(R.id.listTitle);
TextView listTitleTextView = (TextView) convertView.findViewById(R.id.showTextHolder);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBoxHolder);
// checkBox.setSelected(true);
// if (pref.getInt(listTitle, 0) == 1) {
// checkBox.setSelected(true);
// } else {
// checkBox.setSelected(false);
// }
final boolean[] st = new boolean[1];
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// if (!checkBox.isChecked()) {
// ExpandableListView gExpandableListView = (ExpandableListView) groupview;
// gExpandableListView.expandGroup(listPosition);
//// checkBox.setChecked(false);
// RealmResults<ObjectsInGroupRealm> objectsInGroupRealms = RealmController.getObjects(realm, listTitle);
// int position = -1;
// for (ObjectDefExtends objectDefExtends : Singleton.getInstance().getListaODE()) {
// for (ObjectsInGroupRealm o : objectsInGroupRealms) {
// if (o.getName().equals(objectDefExtends.name)) {
// position = Singleton.getInstance().getListaODE().indexOf(objectDefExtends);
// Singleton.getInstance().getListaODE().get(position).visible = false;
// editor.putInt(Singleton.getInstance().getListaODE().get(position).id.toString(), 0);
// editor.apply();
// RealmController.updateGroup(o.getGroupName(), false, realm);
// RealmController.updateObjectsInGroupRealm(o.getGroupName(), realm, context, false);
// FragmentGroupObjectsActivity.getArgument(context);
// }
// }
// }
// selected.remove(Integer.valueOf(listPosition));
// } else {
// ExpandableListView gExpandableListView = (ExpandableListView) groupview;
// gExpandableListView.expandGroup(listPosition);
//// checkBox.setChecked(true);
// selected.add(listPosition);
// RealmResults<ObjectsInGroupRealm> objectsInGroupRealms = RealmController.getObjects(realm, listTitle);
// int position = -1;
// for (ObjectDefExtends objectDefExtends : Singleton.getInstance().getListaODE()) {
// for (ObjectsInGroupRealm o : objectsInGroupRealms) {
// if (o.getName().equals(objectDefExtends.name)) {
// position = Singleton.getInstance().getListaODE().indexOf(objectDefExtends);
// Singleton.getInstance().getListaODE().get(position).visible = true;
// editor.putInt(Singleton.getInstance().getListaODE().get(position).id.toString(), 1);
// editor.apply();
// RealmController.updateGroup(o.getGroupName(), true, realm);
// st[0] = true;
// checkBox.setChecked(true);
// RealmController.updateObjectsInGroupRealm(o.getGroupName(), realm, context, true);
// FragmentGroupObjectsActivity.getArgument(context);
// }
// }
// }
// }
// FragmentGroupObjectsActivity.getArgument(context);
// FragmentAllObjectActivity.getArgument(context);
// notifyDataSetChanged();
}
});
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
// checkBox.setChecked(false);
RealmResults<ObjectsInGroupRealm> objectsInGroupRealms = RealmController.getObjects(realm, listTitle);
int position = -1;
for (ObjectDefExtends objectDefExtends : Singleton.getInstance().getListaODE()) {
for (ObjectsInGroupRealm o : objectsInGroupRealms) {
if (o.getName().equals(objectDefExtends.name)) {
position = Singleton.getInstance().getListaODE().indexOf(objectDefExtends);
Singleton.getInstance().getListaODE().get(position).visible = false;
editor.putInt(Singleton.getInstance().getListaODE().get(position).id.toString(), 0);
editor.apply();
RealmController.updateGroup(o.getGroupName(), false, realm);
RealmController.updateObjectsInGroupRealm(o.getGroupName(), realm, context, false);
FragmentGroupObjectsActivity.getArgument(context);
}
}
}
selected.remove(Integer.valueOf(listPosition));
} else {
// checkBox.setChecked(true);
selected.add(listPosition);
RealmResults<ObjectsInGroupRealm> objectsInGroupRealms = RealmController.getObjects(realm, listTitle);
int position = -1;
for (ObjectDefExtends objectDefExtends : Singleton.getInstance().getListaODE()) {
for (ObjectsInGroupRealm o : objectsInGroupRealms) {
if (o.getName().equals(objectDefExtends.name)) {
position = Singleton.getInstance().getListaODE().indexOf(objectDefExtends);
Singleton.getInstance().getListaODE().get(position).visible = true;
editor.putInt(Singleton.getInstance().getListaODE().get(position).id.toString(), 1);
editor.apply();
RealmController.updateGroup(o.getGroupName(), true, realm);
st[0] = true;
checkBox.setChecked(true);
RealmController.updateObjectsInGroupRealm(o.getGroupName(), realm, context, true);
FragmentGroupObjectsActivity.getArgument(context);
}
}
}
}
FragmentGroupObjectsActivity.getArgument(context);
FragmentAllObjectActivity.getArgument(context);
notifyDataSetChanged();
}
});
listTitleTextView.setTypeface(null, Typeface.BOLD);
listTitleTextView.setText(listTitle);
checkBox.setChecked(RealmController.getGroup(listTitleTextView.getText().toString(), realm).isSelect());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
}
Related
I am getting data in String[] from another class with intent. I show the data I received in listview. When I click the deleteshop button on the custom adapter, I want the data I clicked to be deleted from the String array. How can I do that?
My code;
final ListView list = findViewById(R.id.list);
final ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
final String[] cartList = getIntent().getStringArrayExtra("saleData");
arrayList.add(new SubjectData("", ""));
final int cartListLength = cartList.length;
int counter = 0;
String lastItem = "";
for (String e : cartList) {
counter += 1;
if (e == "" || e == null) {
lastItem = cartList[counter-3];
break;
}
String productPhoto = "";
switch (e) {
case "1 PC GREEN COLA x 10.00 TL":
productPhoto = "cc";
break;
default:
productPhoto = "";
break; }
arrayList.add(new SubjectData(e, productPhoto));;
}
arrayList.remove(arrayList.size()-1);
arrayList.remove(arrayList.size()-1);
final CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);
nextButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
nextButton.setImageResource(R.drawable.next_down);
break;
case MotionEvent.ACTION_UP:
nextButton.setImageResource(R.drawable.next_up);
Intent myIntent = new Intent(getApplicationContext(), PrinterManagerActivity.class);
myIntent.putExtra("saleData", cartList);
startActivityForResult(myIntent, 0);
//
break;
}
return true;
}
});
SubjectData model class:
String SubjectName;
String Image;
public SubjectData(String subjectName, String image) {
this.SubjectName = subjectName;
this.Image = image;
}
Customadapter;
class CustomAdapter implements ListAdapter {
ArrayList<SubjectData> arrayList;
Context context;
public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SubjectData subjectData=arrayList.get(position);
if(convertView==null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView=layoutInflater.inflate(R.layout.list_row, null);
TextView tittle=convertView.findViewById(R.id.title);
ImageView imag=convertView.findViewById(R.id.list_image);
ImageView
deleteshop=convertView.findViewById(R.id.deleteshop);
deleteshop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (context instanceof SaleSummary) {
((SaleSummary)context).deleteItem(position);
int selectedFromList = (int) list.getItemAtPosition(position);
String gettextdata = tittle.getText().toString();
Toast.makeText(context, gettextdata""+"the product has been deleted
", Toast.LENGTH_LONG).show();
}
}
});
tittle.setText(subjectData.SubjectName);
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(subjectData.Image, "drawable",
context.getPackageName());
imag.setImageResource(resourceId);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
listview design;
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip">
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/title"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:gravity="center"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
<ImageView
android:layout_gravity="center"
android:id="#+id/deleteshop"
android:src="#drawable/negative"
android:layout_width="25dp"
android:layout_height="25dp" ></ImageView>
</LinearLayout>
This is basically removing data from an Array which is normal programming / data structure task.
You can run a for loop on cartList and when you encounter the item you wish to delete you can simply overwrite that item with next item until you get to end of list then you mark the last item as null.
for(int i ==0; i < cartList.length(); i++){
if(cartList[i] == selectedItem){
for(int j = i j < cartList.length(); j++){
cartList[j] == cartList[j++];
}
// mark last item as null
cartList[cartList.length()-1] = null;
break;
}
}
All you need now is a listener between your activity and adapter that will trigger the logic whenever user clicks on delete item on any item.
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 am trying to develop an android app. In my app I am using text view for displaying the available BLE devices. But instead of text view I want to use list view. What changes are needed in my code? I am confusing about how to use list view and various adapters!
Here I provide my code.
MainActivity
public class MainActivity extends AppCompatActivity {
BluetoothManager btManager;
BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;
Button startScanningButton;
Button stopScanningButton;
TextView peripheralTextView;
private final static int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
peripheralTextView = (TextView) findViewById (R.id.PeripheralTextView);
peripheralTextView.setMovementMethod(new ScrollingMovementMethod());
startScanningButton = (Button) findViewById(R.id.StartScanButton);
startScanningButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startScanning();
}
});
stopScanningButton = (Button) findViewById(R.id.StopScanButton);
stopScanningButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopScanning();
}
});
stopScanningButton.setVisibility(View.INVISIBLE);
btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
btScanner = btAdapter.getBluetoothLeScanner();
if (btAdapter != null && !btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
}
}
// Device scan callback.
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() + "\n");
// auto scroll for text view
final int scrollAmount = peripheralTextView.getLayout ().getLineTop (peripheralTextView.getLineCount())- peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
};
public void startScanning() {
System.out.println("start scanning");
peripheralTextView.setText("");
startScanningButton.setVisibility(View.INVISIBLE);
stopScanningButton.setVisibility(View.VISIBLE);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
btScanner.startScan(leScanCallback);
}
});
}
public void stopScanning() {
System.out.println("stopping scanning");
peripheralTextView.append("Stopped Scanning");
startScanningButton.setVisibility(View.VISIBLE);
stopScanningButton.setVisibility(View.INVISIBLE);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
btScanner.stopScan(leScanCallback);
}
});
}
}
activity_main.xml
<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"
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.nc.android.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Bluetooth Scanners!" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Scan"
android:id="#+id/StartScanButton"
android:layout_marginTop="40dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Stop Scanning"
android:id="#+id/StopScanButton"
android:layout_marginTop="40dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:id="#+id/PeripheralTextView"
android:scrollbars="vertical"
android:maxLines="30" />
</RelativeLayout>
public ArrayList<model_> countries_lang = new ArrayList<model_>();
Adapter_search adapt;
in your postexceute
adapt = new Adapter_search(getActivity(), yourdata);
lv.setAdapter(adapt);
Adapter class
public class Adapter_search extends BaseAdapter
Context c;
ArrayList<model_> players;
CustomFilter filter;
ArrayList<model_> filterList;
SessionManager session;
boolean isSet;
Adapter_search myAdapter;
private int selectedPosition = 0;
public Adapter_search(Context ctx, ArrayList<model_> players) {
// TODO Auto-generated constructor stub
this.c = ctx;
this.players = players;
this.filterList = players;
session = new SessionManager(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return players.size();
}
#Override
public Object getItem(int pos) {
// TODO Auto-generated method stub
return players.get(pos);
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
/* int itemID;
// orig will be null only if we haven't filtered yet:
if (players == null)
{
itemID = pos;
}
else
{
itemID = players.indexOf(filterList.get(pos));
}
return itemID;*/
return players.indexOf(getItem(pos));
}
#Override
public View getView(final int pos, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
myAdapter = new Adapter_search(c, players);
LayoutInflater inflater = (LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.search_popup, null);
}
TextView nameTxt = (TextView) convertView.findViewById(R.id.textView_titllename);
final ImageView img = (ImageView) convertView.findViewById(R.id.tick);
//SET DATA TO THEM
nameTxt.setText(players.get(pos).getLangName());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notifyDataSetChanged();
// Toast.makeText(c, players.get(pos).getLangName() + "+" +
players.get(pos).getid(), Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
}
I have a problem with my BaseAdapter.
When I add items to my listview I get this:
When I remove the items one by one I get this problem:
BaseAdapter.java
public class TipsterAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
AlertDialog dialog;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
private LayoutInflater mInflater;
DataBase datb;
ImageButton removeBttn;
ImageButton editBttn;
Button visit;
public TipsterAdapter(Context context, DataBase datb) {
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.datb = datb;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
if(list.size() == 0) {
return null;
}
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
//just return 0 if your list items do not have an Id variable.
}
public static class ViewHolder {
public TextView textView;
}
#Override
public int getItemViewType(int position) {
return sectionHeader.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return 2;
}
public void addItem(final String item) {
list.add(item);
notifyDataSetChanged();
}
public void addSectionHeaderItem(final String item) {
list.add(item);
sectionHeader.add(list.size() - 1);
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
final View bieg = convertView;
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView.findViewById(R.id.textView1);
removeBttn = (ImageButton)convertView.findViewById(R.id.remove_btn);
editBttn = (ImageButton)convertView.findViewById(R.id.edit_btn);
visit = (Button) convertView.findViewById(R.id.visitar);
if(getItem(position).toString().equals("Los tipsters agregados aparecerán aquí")) {
holder.textView.setTextSize(15);
removeBttn.setVisibility(View.INVISIBLE);
editBttn.setVisibility(View.INVISIBLE);
visit.setVisibility(View.INVISIBLE);
} else if (getItem(position).toString().equals("TasmaTenis ITF") || getItem(position).toString().equals("KrlosTM") || getItem(position).toString().equals("GreengoSIR") || getItem(position).toString().equals("Ribe Experience")) {
removeBttn.setVisibility(View.INVISIBLE);
editBttn.setVisibility(View.INVISIBLE);
visit.setVisibility(View.VISIBLE);
} else {
visit.setVisibility(View.INVISIBLE);
removeBttn.setVisibility(View.VISIBLE);
editBttn.setVisibility(View.VISIBLE);
}
visit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getItem(position).toString().equals("KrlosTM")) {
String url = "https://t.me/KrlosTMpicks";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} else if(getItem(position).toString().equals("TasmaTenis ITF")) {
String url = "https://t.me/TasmaPicksTenis";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} else if(getItem(position).toString().equals("GreengoSIR")) {
String url = "https://t.me/GreengoSIR";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} else if(getItem(position).toString().equals("Ribe Experience")) {
String url = "https://t.me/ribexperience";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
} else {
}
}
}
);
final View finalConvertView = convertView;
final ViewHolder finalHolder = holder;
removeBttn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
OperacionesBaseDatos db = new OperacionesBaseDatos();
db.eliminarTipster(getItem(position).toString());
Toast.makeText(v.getContext(), "Tipster borrado", Toast.LENGTH_LONG).show();
list.clear();
sectionHeader = new TreeSet<Integer>();
list = new ArrayList<String>();
notifyDataSetChanged();
Cursor cursor=datb.GetAllTipsterData();
list.clear();
addSectionHeaderItem("Mis Tipsters");
SQLiteDatabase db2 = datb.getWritableDatabase();
long numRows = DatabaseUtils.queryNumEntries(db2, "tipster");
if(numRows==0) {
final ImageButton removeBttn = (ImageButton) finalConvertView.findViewById(R.id.remove_btn);
final ImageButton editBttn = (ImageButton) finalConvertView.findViewById(R.id.edit_btn);
final Button visit = (Button) finalConvertView.findViewById(R.id.visitar);
Activity act = (Activity)context;
act.runOnUiThread(new Runnable(){
#Override
public void run() {
removeBttn.setVisibility(View.INVISIBLE);
editBttn.setVisibility(View.INVISIBLE);
visit.setVisibility(View.INVISIBLE);
} });
addItem("Los tipsters agregados aparecerán aquí");
}
while(cursor.moveToNext()) {
addItem(cursor.getString(0));
}
addSectionHeaderItem("Tipsters Recomendados");
addItem("TasmaTenis ITF");
addItem("KrlosTM");
addItem("GreengoSIR");
addItem("Ribe Experience");
datb.close();
notifyDataSetChanged();
}
});
editBttn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(final View v23) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(new ContextThemeWrapper(v23.getContext(), R.style.AlertDialogCustom));
alertDialog.setTitle("Editar Tipster");
alertDialog.setTitle("Editar Tipster");
alertDialog.setMessage("Escribe el nuevo nombre del tipster:");
final EditText input = new EditText(v23.getContext());
input.setTextColor(ContextCompat.getColor(v23.getContext(), android.R.color.black));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
alertDialog.setPositiveButton("Cambiar",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String fechaActual = Calendar.getInstance().getTime().toString();
//if (string.trim().length() == 0) {
try {
SQLiteDatabase db=datb.getWritableDatabase();
String sql="UPDATE tipster set nombre='" + input.getText().toString() + "' where nombre like '" + getItem(position).toString() + "'";
try{
db.execSQL(sql);
}catch(SQLException ex){
Log.d(TAG,"update data failure");
}
} finally {
Toast.makeText(v23.getContext(),
"Tipster modificado", Toast.LENGTH_SHORT).show();
}
list.clear();
sectionHeader = new TreeSet<Integer>();
Cursor cursor=datb.GetAllTipsterData();
addSectionHeaderItem("Mis Tipsters");
while(cursor.moveToNext()) {
addItem(cursor.getString(0));
}
addSectionHeaderItem("Tipsters Recomendados");
addItem("TasmaTenis ITF");
addItem("KrlosTM");
addItem("GreengoSIR");
addItem("Ribe Experience");
datb.close();
notifyDataSetChanged();
}
});
alertDialog.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog = alertDialog.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
});
input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
// Check if edittext is empty
if (TextUtils.isEmpty(s) || s.toString().trim().length() == 0) {
// Disable ok button
((AlertDialog) dialog).getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(false);
} else {
// Something into edit text. Enable the button.
((AlertDialog) dialog).getButton(
AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
}
});
dialog.show();
notifyDataSetChanged();
}
});
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.listview_sections, null);
holder.textView = (TextView) convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(list.get(position));
View view = convertView;
//Handle TextView and display string from your list
//TextView listItemText = (TextView)view.findViewById(R.id.textView1);
//listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
//holder.textView.setText(list.get(position));
return view;
}
An I call this from Tipster.java with this:
public void displayList(View view){
db = new DataBase ((MainActivity)getActivity());
Cursor cursor=db.GetAllTipsterData();
ArrayList<String> mArrayList = new ArrayList<String>();
adapter = new TipsterAdapter((MainActivity)getActivity(), db);
adapter.addSectionHeaderItem("Mis Tipsters");
Log.e("COLUMNAS: ", ""+cursor.getColumnCount());
SQLiteDatabase db2 = db.getWritableDatabase();
long numRows = DatabaseUtils.queryNumEntries(db2, "tipster");
if(numRows==0) {
adapter.addItem("Los tipsters agregados aparecerán aquí");
}
while(cursor.moveToNext()) {
adapter.addItem(cursor.getString(0));
}
adapter.addSectionHeaderItem("Tipsters Recomendados");
adapter.addItem("TasmaTenis ITF");
adapter.addItem("KrlosTM");
adapter.addItem("GreengoSIR");
adapter.addItem("Ribe Experience");
ListView lv = (ListView) view.findViewById(R.id.listita);
lv.setAdapter(adapter);
db.close();
}
row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="20sp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/remove_btn"
android:layout_width="50dp"
android:src="#drawable/ic_removebttn"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_alignTop="#+id/edit_btn"
android:layout_alignBottom="#+id/edit_btn" />
<ImageButton
android:id="#+id/edit_btn"
android:layout_width="50dp"
android:src="#drawable/ic_editbttn"
android:layout_height="50dp"
android:layout_toLeftOf="#id/remove_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp" />
<Button
android:text="Visitar"
android:layout_width="89dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/remove_btn"
android:id="#+id/visitar"
android:visibility="gone"
android:layout_alignRight="#+id/remove_btn"
android:layout_alignEnd="#+id/remove_btn" />
listview_sections.xml
<?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="wrap_content"
android:background="#52b1ff"
android:gravity="center_vertical" >
<TextView
android:id="#+id/textSeparator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="8dp"
android:text=""
android:textAllCaps="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
android:textStyle="bold"
android:visibility="visible" />
</LinearLayout>
Hope anybody can help me. Thanks!
Be sure to add and remove items of the ListView thru the Adapter. After adding/removing items call the function below to reflect your changes.
adapter.notifyDataSetChanged();
Hope this works for you.
Could you please tell me why my image not change when I change my expand and collapse the list view .Both time I got same image ..I will show in below image when I expand it display (+) image .why ?
here is my code .
Main activity
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if(listDataHeader.get(groupPosition) != null)
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Top 250");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");
// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");
List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");
/*List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");*/
listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
listDataChild.put(listDataHeader.get(1), nowShowing);
listDataChild.put(listDataHeader.get(2), null);
}
}
Adapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
if(this._listDataChild.get(this._listDataHeader.get(groupPosition))!=null)
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
return 0;
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
View ind = convertView.findViewById( R.id.explist_indicator);
if( ind != null ) {
ImageView indicator = (ImageView)ind;
if( getChildrenCount( groupPosition ) == 0 ) {
indicator.setVisibility( View.INVISIBLE );
} else {
indicator.setVisibility( View.VISIBLE );
int stateSetIndex = ( isExpanded ? 1 : 0) ;
Drawable drawable = indicator.getDrawable();
}
}
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
activity.xml
<?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:orientation="vertical"
android:background="#f4f4f4" >
<ExpandableListView
android:id="#+id/lvExp"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:cacheColorHint="#00000000"
android:groupIndicator="#android:color/transparent"
/>
</LinearLayout>
list_group.xml
<?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="wrap_content"
android:orientation="horizontal"
android:padding="8dp"
android:background="#000000">
<ImageView android:src="#drawable/test"
android:id="#+id/explist_indicator"
android:layout_width="20px"
android:layout_height="20px"/>
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="17dp"
android:textColor="#f9f93d" />
</LinearLayout>
list_item.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="55dip"
android:orientation="vertical" >
<TextView
android:id="#+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="#000000"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />
</LinearLayout>][1]
I solve that problem by own .Like that
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
View ind = convertView.findViewById(R.id.explist_indicator);
if (ind != null) {
ImageView indicator = (ImageView) ind;
if (isExpanded) {
indicator.setImageResource(R.drawable.icon_3);
} else {
indicator.setImageResource(R.drawable.icon_4);
}
if (getChildrenCount(groupPosition) == 0) {
indicator.setVisibility(View.INVISIBLE);
} else {
indicator.setVisibility(View.VISIBLE);
}
}
return convertView;
}
change Image view like that
<ImageView
android:id="#+id/explist_indicator"
android:layout_width="20px"
android:layout_height="20px"
android:src="#drawable/icon_4" />