Deleting items in ListView with BaseAdapter - java

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.

Related

how to callback from fragment to activity With bottom sheet

Hey I'm doing filtering data on my project using bottom Sheet with view-pager and two fragments i can pass data from activity to view-pager adapter and get in fragment through constructor but how can i get data from fragment to activity using bottom-sheet
this is how i send data from activity
adapter = new PagerAdapters(this.getSupportFragmentManager(),
tabLayout.getTabCount(),_id);
and receive data with constructor in fragment
public Filterfragment(String _id) {
this._id = _id;
}
And I'm using recyclerview to show data like this
So how can i send id of the item to activity so i can reload my recyclerview data when the apply button click.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_sheet"
android:background="#android:color/white"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabPadding="0dp"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_below="#id/tabs"
android:layout_above="#id/applyBtn"
android:layout_height="match_parent"
/>
<Button
android:id="#+id/applyBtn"
android:layout_width="match_parent"
android:text="Apply"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content" />
</RelativeLayout>
This is main recyclerview adapter
public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.FilterViewHolder> {
private static final String TAG = "FilterAdapter";
Context context;
List<TagTypeResult> tagTypeModels;
public static int current_pos = -1;
TagAdapter tagAdapter;
int rotationAngle = 0;
public FilterAdapter(Context context, List<TagTypeResult> tagTypeModels) {
this.context = context;
this.tagTypeModels = tagTypeModels;
}
#NonNull
#Override
public FilterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.filter_row_item,parent,false);
return new FilterAdapter.FilterViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull FilterViewHolder filterViewHolder, int i) {
TagTypeResult tagTypeModel = tagTypeModels.get(i);
filterViewHolder.txt.setText(tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
if (tagTypeModel.getTagsLists() != null) {
if (tagTypeModel.getTagsLists().size() <= 0) {
filterViewHolder.arrow.setVisibility(View.GONE);
filterViewHolder.arrow.setRotationX(180);
} else {
filterViewHolder.arrow.setVisibility(View.VISIBLE);
filterViewHolder.arrow.setRotationX(0);
}
}else {
filterViewHolder.arrow.setVisibility(View.GONE);
}
tagAdapter = new TagAdapter(context, tagTypeModel.getTagsLists(), new TagInterface() {
#Override
public void tagClick(View view, int pos, String tagID) {
Log.d(TAG, "tagClick: "+tagID);
}
});
filterViewHolder.sub_list_recycler.setAdapter(tagAdapter);
tagAdapter.notifyDataSetChanged();
if (current_pos == filterViewHolder.getAdapterPosition()){
if (filterViewHolder.sub_list_recycler.getVisibility() == View.GONE) {
filterViewHolder.sub_list_recycler.setVisibility(View.VISIBLE);
}else {
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}else {
Log.i(TAG, "onBindViewHolder: sublist gone "+tagTypeModel.getName());
filterViewHolder.sub_list_recycler.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return tagTypeModels.size();
}
class FilterViewHolder extends RecyclerView.ViewHolder {
TextView txt;
ImageView arrow;
RecyclerView sub_list_recycler;
RelativeLayout linearLayout;
FilterViewHolder(#NonNull View itemView) {
super(itemView);
txt = itemView.findViewById(R.id.txt);
arrow = itemView.findViewById(R.id.arrow);
linearLayout = itemView.findViewById(R.id.main_cat_lay);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "onClick: "+current_pos);
if (current_pos != getAdapterPosition()) {
current_pos = getAdapterPosition();
notifyDataSetChanged();
}
else{
current_pos = -1;
notifyDataSetChanged();
}
}
});
sub_list_recycler = itemView.findViewById(R.id.sub_list_recycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context) {
#Override
public boolean canScrollVertically() {
return false;
}
};
sub_list_recycler.setLayoutManager(mLayoutManager);
sub_list_recycler.addItemDecoration(new SimpleDividerItemDecoration(context));
}
}
}
sub recyclerView adapter :
public class TagAdapter extends RecyclerView.Adapter<TagAdapter.TagViewHolder> {
private static final String TAG = "SublistAdapter";
Context context;
List<TagsList> tagsLists;
int pos = -1;
TagInterface tagInterface;
public TagAdapter(Context context, List<TagsList> tagsLists,TagInterface tagInterface) {
this.context = context;
this.tagsLists = tagsLists;
this.tagInterface = tagInterface;
}
#NonNull
#Override
public TagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tag_item,parent,false);
return new TagAdapter.TagViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull TagViewHolder tagViewHolder, int i) {
TagsList tagsList = tagsLists.get(i);
tagViewHolder.tagtxt.setText(tagsList.getName());
if (tagsList.isChecked()){
tagViewHolder.tagName.setChecked(true);
}else {
tagViewHolder.tagName.setChecked(false);
}
}
#Override
public int getItemCount() {
return tagsLists.size();
}
public class TagViewHolder extends RecyclerView.ViewHolder {
TextView tagtxt;
CheckBox tagName;
RelativeLayout childClik;
public TagViewHolder(#NonNull View itemView) {
super(itemView);
//pri_txt = itemView.findViewById(R.id.pri_txt);
tagName = itemView.findViewById(R.id.tagName);
tagtxt = itemView.findViewById(R.id.tagtxt);
childClik = itemView.findViewById(R.id.childClik);
tagName.setEnabled(false);
childClik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = true;
if (isChecked)
{
tagsLists.get(getAdapterPosition()).setChecked(true);
tagName.setChecked(true);
tagInterface.tagClick(v,getAdapterPosition(),tagsLists.get(getAdapterPosition()).get_id());
Toast.makeText(context, "[pos]"+tagsLists.get(getAdapterPosition()).get_id(), Toast.LENGTH_SHORT).show();
}else
{
tagsLists.get(getAdapterPosition()).setChecked(false);
tagName.setChecked(false);
}
}
});
}
}
}

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!

How to code for the list view in android studio instead of text view

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

Android: TextView setText in custom adapter not changing the UI

I'm trying to make a dictionary with two TextViews - 1 for the word, 1 for the translation. On long press, an edit button will popup that will show an alert dialog on click. The alert dialog takes two inputs, new word and new translation, edits the old word, and sets the TextView to these words.
The problem is that the setText in the alert dialog doesn't change the UI (setBGcolor and setAllCaps work though). Only after resetting the Activity in which I use the adapter do the changes show.
public class DictionaryAdapter extends ArrayAdapter<String> {
private LayoutInflater inflater;
private int layout;
private Map<String, String> dict;
private boolean[] visibleButtons;
private Context mContext;
static class ViewHolder {
TextView word;
TextView translation;
FloatingActionButton edit;
}
public DictionaryAdapter(Context context, int layout, Map<String, String> source) {
super(context, layout, new ArrayList<>(source.keySet()));
mContext = context;
inflater = LayoutInflater.from(context);
this.layout = layout;
dict = source;
visibleButtons = new boolean[dict.size()];
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull final ViewGroup parent) {
final String word = getItem(position);
final String translation = dict.get(word);
final ViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(layout, null, false);
holder = new ViewHolder();
holder.word = (TextView) convertView.findViewById(R.id.dictWord);
holder.translation = (TextView) convertView.findViewById(R.id.dictTranslation);
holder.edit = convertView.findViewById(R.id.editTranslation);
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
holder.word.setText(word);
holder.translation.setText(translation);
if(position < visibleText.length) {
if (visibleButtons[position]) {
holder.edit.setVisibility(View.VISIBLE);
} else {
holder.edit.setVisibility(View.GONE);
}
}
holder.word.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if(holder.edit.getVisibility() == View.VISIBLE) {
holder.edit.setVisibility(View.GONE);
visibleButtons[position] = false;
}
else {
holder.edit.setVisibility(View.VISIBLE);
visibleButtons[position] = true;
}
return true;
}
});
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
View showDialog = inflater.inflate(R.layout.add_new_word_popup, parent, false);
final EditText editTextWord = (EditText) showDialog.findViewById(R.id.wordInput);
final EditText editTextTranslation = (EditText) showDialog.findViewById(R.id.translationInput);
Button addWordButton = (Button) showDialog.findViewById(R.id.button_confirm_word);
addWordButton.setText(R.string.edit_WordTrans_button);
builder.setView(showDialog);
final AlertDialog dialog = builder.create();
dialog.show();
addWordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String wordInput = editTextWord.getText().toString();
final String translationInput = editTextTranslation.getText().toString();
boolean addable = true;
if(wordInput.replaceAll("\\s+","").isEmpty()) {
Toast.makeText(mContext, R.string.no_word_err, Toast.LENGTH_SHORT).show();
addable = false;
}
if (translationInput.replaceAll("\\s+","").isEmpty()) {
Toast.makeText(mContext, R.string.no_translation_err, Toast.LENGTH_SHORT).show();
addable = false;
}
if(addable) {
editWord(holder.word.getText().toString(), wordInput, translationInput);
holder.word.setText(wordInput);
holder.translation.setText(translationInput);
notifyDataSetChanged();
Toast.makeText(mContext, R.string.edited_word_msg, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
});
}
});
return convertView;
}
private void editWord(String oldWord, String newWord, String newTranslation) {
MainApplication.getDataUtils().editWordInDict(mContext, DictionaryActivity.currentDictionaryName,
oldWord, newWord, newTranslation); // edits the word in sharedPreferences
dict.remove(oldWord);
dict.put(newWord, newTranslation);
notifyDataSetChanged();
}
What I've tried but didn't quite work:
This updated the TextView. But when I tried to edit another word, the first word showed the original word again.
holder.word.post(new Runnable() {
#Override
public void run() {
holder.word.setText(wordInput);
holder.translation.setText(translationInput);
}
});
This had no effect at all:
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
holder.word.setText(wordInput);
holder.translation.setText(translationInput);
}
});
I also tried calling this method (same effect as with holder.word.post method):
private void changeText(final ViewHolder holder, final String newWord, final String newTranslation) {
final Runnable mUpdateText = new Runnable() {
public void run() {
holder.word.setText(newWord);
holder.translation.setText(newTranslation);
}
};
mHandler.post(mUpdateText);
}
This is the dialog layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingStart="10dip">
<TextView
android:id="#+id/dictWord"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
android:textSize="25sp" />
<TextView
android:id="#+id/dictTranslation"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/dictWord"
android:background="?android:attr/selectableItemBackground"
android:textSize="25sp"
android:textStyle="bold"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/editTranslation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="58dp"
android:clickable="true"
android:focusable="true"
android:visibility="gone"
app:backgroundTint="#android:color/transparent"
app:srcCompat="#android:drawable/ic_menu_edit" />
</RelativeLayout>

Multi selection in recyclerview is not working

Long click on row of recyclerview is not entered in onClick() I dont understand what is wrong with my code.Following are my MainActivity, adapter and row of my recyclerview which is made using cardview.
Following is my MainActivity.java
public class MainActivity extends AppCompatActivity implements RecyclerView.OnItemTouchListener,
View.OnClickListener,
ActionMode.Callback {
ArrayList<ProductPojo> lastNameList;
private RecyclerView recyclerView;
private ProductAdapter adapter;
private List<ProductPojo> albumList;
GestureDetectorCompat gestureDetector;
ActionMode actionMode;
/////
private ProgressDialog pDialog;
ApiClass apigetOfferList;
String response;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
albumList = new ArrayList<>();
lastNameList = new ArrayList<ProductPojo>(12);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(MainActivity.this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View v, final int position) {
Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
final EditText edittext = new EditText(MainActivity.this);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setMessage("Enter Your Last Name");
alert.setTitle("Fill me");
alert.setView(edittext);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
ProductPojo lNamePojo = new ProductPojo(edittext.getText().toString());
Log.d("lastNameList.size()", ""+lastNameList.size() +" "+position);
if(!albumList.isEmpty() && lastNameList.size() != 0) {
lastNameList.add(position, lNamePojo);
Log.d("lastNameList.size()", ""+lastNameList.size());
}
adapter.notifyDataSetChanged();
adapter = new ProductAdapter(MainActivity.this, albumList, lastNameList);
recyclerView.setAdapter(adapter);
// lName = edittext.getText().toString();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
})
);
/* LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter( adapter );*/
gestureDetector = new GestureDetectorCompat(this, new RecyclerViewDemoOnGestureListener());
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute();
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
private class ListViewLoaderTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
apigetOfferList = new ApiClass();
}
#Override
protected String doInBackground(String... args) {
response = apigetOfferList.xmlFetchFunction();
return response;
}
#Override
protected void onPostExecute(String res) {
Log.d("res", "" + res);
StringReader reader = new StringReader(res);
ProductXmlParser productXmlParser = new ProductXmlParser();
List<HashMap<String, String>> products = null;
try {
/** Getting the parsed data as a List construct */
products = productXmlParser.parse(reader);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
Log.d("products", "" + products);
for (int i = 0; i < products.size(); i++) {
Log.d("productThumbnail", "" + products.get(i).get("productThumbnail"));
ProductPojo album = new ProductPojo(products.get(i).get("productThumbnail"), products.get(i).get("productName"), products.get(i).get("categoryName"), products.get(i).get("productDescription"), products.get(i).get("numberOfRatings"), products.get(i).get("rating"), products.get(i).get("averageRatingImageURL"));
albumList.add(album);
lastNameList.add(album);
}
adapter = new ProductAdapter(MainActivity.this, albumList, lastNameList);
adapter.notifyDataSetChanged();
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(MainActivity.this, 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
pDialog.dismiss();
}
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {//in
Log.d("RecyclerView","DemoActivity"+"onInterceptTouchEvent");
gestureDetector.onTouchEvent(e);
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
private void myToggleSelection(int idx) {//in
Log.d("RecyclerView","DemoActivity"+"myToggleSelection");
adapter.toggleSelection(idx);
String title = getString(R.string.selected_count, adapter.getSelectedItemCount());
actionMode.setTitle(title);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
if (view.getId() == R.id.container_list_item) {//in
// item click
Log.d("RecyclerView","DemoActivity"+"item click");
int idx = recyclerView.getChildLayoutPosition(view);
if (actionMode != null) {
myToggleSelection(idx);
return;
}
}
}
private class RecyclerViewDemoOnGestureListener extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {//in
Log.d("RecyclerView","DemoActivity"+"onSingleTapConfirmed");
View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
onClick(view);
return super.onSingleTapConfirmed(e);
}
public void onLongPress(MotionEvent e) {//in
Log.d("RecyclerView","DemoActivity"+"onLongPress");
View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (actionMode != null) {
return;
}
// Start the CAB using the ActionMode.Callback defined above
actionMode = startActionMode(MainActivity.this);
int idx = recyclerView.getChildAdapterPosition(view);
myToggleSelection(idx);
super.onLongPress(e);
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {//in
// Inflate a menu resource providing context menu items
Log.d("RecyclerView","DemoActivity"+"onCreateActionMode");
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.menu_cab_recyclerviewdemoactivity, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
This is my Adapter class
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {
private Context mContext;
private List<ProductPojo> albumList;
String lName;
private List<DemoModel> items;
private SparseBooleanArray selectedItems;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView lastName, cat_name, product_name, product_design, numOfRatings, rate;
public ImageView thumbnail1, thumbnail2;
public MyViewHolder(View view) {
super(view);
lastName = (TextView) view.findViewById(R.id.lastName);
product_name = (TextView) view.findViewById(R.id.product_name);
product_design = (TextView) view.findViewById(R.id.product_design);
cat_name = (TextView) view.findViewById(R.id.category_name);
rate = (TextView) view.findViewById(R.id.rate);
numOfRatings = (TextView) view.findViewById(R.id.noOfRatings);
thumbnail1 = (ImageView) view.findViewById(R.id.thumbnail);
thumbnail2 = (ImageView) view.findViewById(R.id.thumbnail2);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), " " + getItemId(), Toast.LENGTH_SHORT).show();
}
});
view.setOnLongClickListener(new View.OnLongClickListener()
{
#Override
public boolean onLongClick(View v)
{
Toast.makeText(v.getContext(), "Long Click Listerner Position is " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
return false;
}
}
);
}
}
public ProductAdapter(Context mContext, List<ProductPojo> albumList, ArrayList<ProductPojo> lName) {
this.mContext = mContext;
this.albumList = albumList;
selectedItems = new SparseBooleanArray();
}
public int getSelectedItemCount() {
Log.d("RecyclerViewDemoAdapter","getSelectedItemCount");
return selectedItems.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
ProductPojo album = albumList.get(position);
holder.lastName.setText("Last Name : " + album.getlName());
holder.product_name.setText("Product Name : " + album.getpName());
holder.cat_name.setText("Category Name : " + album.getcName());
holder.product_design.setText("Product Description : " + album.getpDesc());
holder.rate.setText("Rating : " + album.getRating());
holder.numOfRatings.setText("No.of ratings : " + album.getNoOfRatings());
Drawable productDrawable = LoadImageFromProductLink(album.getpLink());
holder.thumbnail1.setImageDrawable(productDrawable);
// loading album cover using Glide library
Glide.with(mContext).load(album.getpLink()).into(holder.thumbnail1);
Drawable rateDrawable = LoadImageFromRateLink(album.getRateLink());
holder.thumbnail2.setImageDrawable(rateDrawable);
// loading album cover using Glide library
Glide.with(mContext).load(album.getRateLink()).into(holder.thumbnail2);
}
private Drawable LoadImageFromProductLink(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
private Drawable LoadImageFromRateLink(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
#Override
public int getItemCount() {
return albumList.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public void toggleSelection(int pos) {
if (selectedItems.get(pos, false)) {
Log.d("RecyclerViewDemoAdapter","IftoggleSelection");
selectedItems.delete(pos);
} else {
Log.d("RecyclerViewDemoAdapter","ElsetoggleSelection");
selectedItems.put(pos, true);
}
notifyItemChanged(pos);
}
}
**And this is my row**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="#dimen/card_margin"
android:elevation="3dp"
card_view:cardCornerRadius="#dimen/card_album_radius">
<LinearLayout
android:id="#+id/container_list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<LinearLayout
android:id="#+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_margin="5dp"
android:clickable="true"
android:padding="5dp"
android:scaleType="fitXY" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/lastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Product Name"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/backdrop_subtitle"
android:textStyle="bold"
android:visibility="gone" />
<TextView
android:id="#+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:text="Product Name"
android:textColor="#color/album_title"
android:textSize="#dimen/album_title" />
<TextView
android:id="#+id/category_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Category Name"
android:textColor="#color/album_title"
android:textSize="#dimen/album_title" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/product_design"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="Product Design"
android:textColor="#color/album_title"
android:textSize="#dimen/album_title" />
<LinearLayout
android:id="#+id/second"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Rate"
android:textColor="#color/album_title"
android:textSize="#dimen/album_title" />
<TextView
android:id="#+id/noOfRatings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="No. of Ratings"
android:textColor="#color/album_title"
android:textSize="#dimen/album_title" />
</LinearLayout>
<ImageView
android:id="#+id/thumbnail2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Please help me guys..I'm waiting for ur answers..Thanks in Advance!
Detail below
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private Article mArticle;
private TextView mNameTextView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mNameTextView = (TextView) itemView.findViewById(R.id.grid_item_article_name_textView);
}
public void bind(Article article) {
mArticle = article;
mNameTextView.setText(article.getName());
}
#Override
public void onClick(View view) {
// Context context = view.getContext();
// mArticle.getName()
}
#Override
public boolean onLongClick(View view) {
// Handle long click
}
}
Handle on item long click on recycler view

Categories