Having-clicks inside RecyclerAdapter on my Recyclerview - android

I was trying to make responsive clicks events inside my RecyclerAdapter. I can't understand the logic behind on it since my data is auto created by API, therefore i have some buttons in my list and I've like to have response by clicking on it.
This is my code:
My Adapter class:
public class EppViewCartAdapter extends RecyclerView.Adapter<EppViewCartAdapter.MyViewHolder> {
View itemView;
ImageView add,less;
private List<EppViewCartDetails> orderData;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView subject,category,brand,neww,newd,old,discount,count,color;
ImageView image;
public MyViewHolder(View view) {
super(view);
subject=view.findViewById(R.id.view_cart_item_subject);
category=view.findViewById(R.id.view_cart_item_category);
brand=view.findViewById(R.id.view_cart_item_brand);
neww=view.findViewById(R.id.view_cart_item_neww);
old=view.findViewById(R.id.view_cart_item_old);
discount=view.findViewById(R.id.view_cart_item_discount);
newd=view.findViewById(R.id.view_cart_item_new_depends_count);
count=view.findViewById(R.id.view_cart_item_count);
image=view.findViewById(R.id.view_cart_item_image);
add=itemView.findViewById(R.id.view_btn_add);
less=itemView.findViewById(R.id.view_btn_less);
}
}
public EppViewCartAdapter(List<EppViewCartDetails> preorderList) {
this.orderData = preorderList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_cart_card_view, parent, false);
//TODO: I was trying to make a set onlcick listener here but it has errors.
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EppViewCartDetails data= orderData.get(position);
double amount = Double.parseDouble(data.getCount())*Double.parseDouble(data.getNeww());
DecimalFormat formatter = new DecimalFormat("#,###.00");
holder.subject.setText(data.getSubject());
holder.category.setText(data.getCategory());
holder.brand.setText(data.getBrand());
holder.neww.setText("₱ "+formatter.format(amount));
holder.newd.setText(data.getNewd());
holder.old.setText(data.getOld());
holder.old.setPaintFlags(holder.old.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.discount.setText(data.getDiscount());
holder.count.setText(data.getCount());
Picasso.with(itemView.getContext()).load("https://eppteststorage.blob.core.windows.net/images/"+data.getImage()).placeholder(R.drawable.small_logo).into(holder.image, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
Log.e("tae tae"," PAkultie");
}
#Override
public void onError() {
}
}
);
}
#Override
public int getItemCount() {
return orderData.size();
}
}
My error trying my OnclickEvent:(upon my //TODO:)
Process: eppmobile.intellismart.com.EPP, PID: 18675
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at eppmobile.intellismart.com.EPP.ViewCart.EppViewCartAdapter.onCreateViewHolder(EppViewCartAdapter.java:58)
at eppmobile.intellismart.com.EPP.ViewCart.EppViewCartAdapter.onCreateViewHolder(EppViewCartAdapter.java:22)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6794)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
My Activity class:
public class EppViewCart extends Fragment {
View inflatedView = null;
EppViewCartDetails items;
private List<EppViewCartDetails> dataitems = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
inflatedView = inflater.inflate(R.layout.fragment_epp_view_cart, container, false);
retriveSQLITE();
return inflatedView;
}
private void retriveSQLITE() {
SqLiteDB sql = new SqLiteDB(getContext());
SQLiteDatabase db = sql.getWritableDatabase();
Cursor c = sql.retrieveAddToCart(db);
ArrayList<AddToCartModel> get = new ArrayList<>();
while (c.moveToNext()) {
final AddToCartModel details = new AddToCartModel();
details.setID(c.getString(c.getColumnIndexOrThrow("ID")));
details.setDateTime(c.getString(c.getColumnIndexOrThrow("DateTime")));
details.setID_ProductMasterListV(c.getString(c.getColumnIndexOrThrow("ID_ProductMasterListV")));
details.setImageFile(c.getString(c.getColumnIndexOrThrow("ImageFile")));
details.setOrdered(c.getString(c.getColumnIndexOrThrow("Ordered")));
get.add(details);
APICaller service = EppMainFragmentPropertyClient.getRetrofit().create(APICaller.class);
View_Response gets = new View_Response("1", details.getID(), details.getID_ProductMasterListV());
Call<List<View_Data_Properties>> call = service.getView(gets);
call.enqueue(new Callback<List<View_Data_Properties>>() {
#Override
public void onResponse(Call<List<View_Data_Properties>> call, Response<List<View_Data_Properties>> response) {
//Discount
String q = String.format("%.2f", Double.parseDouble(response.body().get(0).getLess()));
long l = Math.round(Double.parseDouble(q));
String percent = l + "%";
double amount = Double.parseDouble(response.body().get(0).getNewPrice());
DecimalFormat formatter = new DecimalFormat("#,###.00");
double amount2 = Double.parseDouble(response.body().get(0).getSRP());
DecimalFormat formatter2 = new DecimalFormat("#,###.00");
items = new EppViewCartDetails(
response.body().get(0).getID(),
response.body().get(0).getName(),
response.body().get(0).getCategory(),
response.body().get(0).getProductsBrand(),
response.body().get(0).getNewPrice(),
"₱ " + formatter.format(amount),
"₱ " + formatter2.format(amount2),
"-" + percent,
details.getOrdered(), response.body().get(0).getHexValue(),
response.body().get(0).getImageFile());
dataitems.add(items);
prepareItems();
}
#Override
public void onFailure(Call<List<View_Data_Properties>> call, Throwable t) {
}
});
}
}
private void prepareItems() {
//Items
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
RecyclerView recyclerView = inflatedView.findViewById(R.id.view_cart_recycler);
recyclerView.setLayoutManager(layoutManager);
EppViewCartAdapter mAdapter = new EppViewCartAdapter(dataitems);
recyclerView.setAdapter(mAdapter);
}
}
My CardView:
<?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="wrap_content">
<RelativeLayout
android:layout_marginTop="8dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/radius_all_two"
android:layout_width="match_parent"
android:layout_height="190dp">
<ImageView
android:layout_width="110dp"
android:layout_height="120dp"
android:src="#drawable/bestseller"
android:id="#+id/view_cart_item_image"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JBL- Grip 100"
android:id="#+id/view_cart_item_subject"
android:textColor="#000"
android:textSize="14dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="25dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_marginTop="15dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category"
android:textColor="#089bcc"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="48dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Headphones"
android:id="#+id/view_cart_item_category"
android:textSize="11dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="48dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Brand"
android:textColor="#089bcc"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="65dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JBL"
android:id="#+id/view_cart_item_brand"
android:textSize="11dp"
android:layout_marginLeft="180dp"
android:layout_marginTop="65dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 1,290.00"
android:id="#+id/view_cart_item_neww"
android:textColor="#00c1ab"
android:textSize="15dp"
android:textStyle="bold"
android:layout_marginLeft="140dp"
android:layout_marginTop="83dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 2,580.00"
android:textSize="11dp"
android:id="#+id/view_cart_item_old"
android:layout_marginLeft="140dp"
android:layout_marginTop="106dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- 50%"
android:textSize="11dp"
android:id="#+id/view_cart_item_discount"
android:layout_marginLeft="210dp"
android:textColor="#ba0101"
android:layout_marginTop="106dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 1,290.00"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:id="#+id/view_cart_item_new_depends_count"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x"
android:textSize="12dp"
android:layout_marginLeft="240dp"
android:textColor="#000"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/left_arrow"
android:text="x"
android:id="#+id/view_cart_item_increment"
android:textSize="12dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/right_arrow"
android:text="x"
android:id="#+id/view_cart_item_decrement"
android:textSize="12dp"
android:layout_marginLeft="304dp"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="31dp"
android:layout_height="16dp"
android:textSize="11dp"
android:textAlignment="center"
android:text="100"
android:id="#+id/view_cart_item_count"
android:layout_marginLeft="270dp"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color"
android:textSize="11dp"
android:textColor="#089bcc"
android:layout_marginLeft="140dp"
android:layout_marginTop="147dp"/>
<ImageView
android:layout_width="34dp"
android:layout_height="17dp"
android:textSize="12dp"
android:id="#+id/view_cart_variant"
android:background="#color/colorPrimaryDark"
android:layout_marginLeft="175dp"
android:layout_marginTop="145dp"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
My Cart_view :
enter image description here
(if you see the "<" and ">" sign, I was trying to add responsive there but it is running in RecyclerView with my adapter so that I didn't know if where could I put my onclick-event.)
My View in recyclerview(I set into comment my //TODO:)
(It is running but no fuction on add and subtract.)
enter image description here
Also, I've try this to (holder.add.setOn...)
enter image description here
And this:(MyViewHolder)
enter image description here

This is null pointer exception you need to understand.
you should replace itemView.findViewById(R.id.view_btn_add) with view.findViewById(R.id.view_btn_add)
because the adapter layout name is view not itemview
just look your code
public MyViewHolder(View view) {
super(view);
}
and you need add click listener either in MyViewHolder() or in onBindViewHolder()
move this code
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});

I found the answer, in my other view cart data, there are the same ID in my xml so that ive just rename my buttons in my xml and inherit it on my class.
My viewCart:
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/left_arrow"
android:text="x"
android:id="#+id/view_cart_item_increment1"
android:textSize="12dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="#drawable/right_arrow"
android:text="x"
android:id="#+id/view_cart_item_decrement1"
android:textSize="12dp"
android:layout_marginLeft="304dp"
android:layout_marginTop="123dp"/>
My Adapter:
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_cart_card_view, parent, false);
add=itemView.findViewById(R.id.view_cart_item_increment1);
less=itemView.findViewById(R.id.view_cart_item_decrement1);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EppViewCartDetails data= orderData.get(position);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
}

The crash is occurs because you are setting click listener on null add view.
First of check your layout file for the all defined IDs in MyViewHolder class. i can't find view_btn_add id in your layout file. So assign it with appropriate view.
And then in your onCreateViewHolder method, you are setting up onClick listener on add view before initialising it.
So move your add.setOnClickListener(...) inside MyViewHolder class after defining all views. So your crash will gone.

Related

trying to iterate spinners RecycleView by clicking a button miss few items

PLEASE READ THE EDIT SECTION BELLOW
I have a Spinners Recyclerview (list) I want to iterate after clicking a button(finishBtn).
in order to get the selected results entered by the user, I try to iterate the list using list.findViewHolderForAdapterPosition.
The size of the list is supposed to be 6 (by viewing Recyclerview I can see all 6) but when I try to iterate, the size is smaller than what actually there is. (instead of 6 the list.getChildCount() is only 3).
Fragment:
public class FragmentUserDetails extends Fragment {
Button finishBtn;
LinkedHashMap<String, ArrayList<String>> detailsQuestions;
DetailsViewModel detailsViewModel;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
detailsViewModel = new ViewModelProvider(this).get(DetailsViewModel.class);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_details, container, false);
detailsQuestions =getQuestions();
Log.d("TAG", "size: "+detailsQuestions.size());
RecyclerView list = view.findViewById(R.id.details_list_rv);
list.setHasFixedSize(true);
list.setLayoutManager(new LinearLayoutManager(getContext()));
DetailsAdapter detailsAdapter = new DetailsAdapter(this);
list.setAdapter(detailsAdapter);
finishBtn = view.findViewById(R.id.userDetails_next_btn);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
finishBtn.setOnClickListener(v -> {
Log.d("TAG", ""+list.getChildCount());
for (int i = 0; i < list.getChildCount(); i++) {
DetailsHolder holder = (DetailsHolder) list.findViewHolderForAdapterPosition(i);
if (holder!=null) {
String question = (String) detailsQuestions.keySet().toArray()[i];
Log.d("TAG", "The answer for " +question+"is :"+ holder.questionSp.getSelectedItem().toString());
}
}
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
});
return view;
}
interface OnItemClickListener {
void onItemClick(int position);
}
public LinkedHashMap<String, ArrayList<String>> getQuestions() {
ArrayList<Detail> arrayList = detailsViewModel.getDetails();
detailsQuestions = new LinkedHashMap<>();
for (Detail detail : arrayList) {
detailsQuestions.put(detail.getQuestion(), detail.getAnswers());
}
return detailsQuestions;
}
}
Adapter:
class DetailsAdapter extends RecyclerView.Adapter<DetailsHolder> {
private final FragmentUserDetails fragmentUserDetails;
FragmentUserDetails.OnItemClickListener listener;
public DetailsAdapter(FragmentUserDetails fragmentUserDetails) {
this.fragmentUserDetails = fragmentUserDetails;
}
public void setOnItemClickListener(FragmentUserDetails.OnItemClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public DetailsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = fragmentUserDetails.getLayoutInflater().inflate(R.layout.details_list_row, parent, false);
DetailsHolder detailsHolder = new DetailsHolder(view, listener);
return detailsHolder;
}
#Override
public void onBindViewHolder(#NonNull DetailsHolder detailsHolder, int position) {
if(fragmentUserDetails.detailsQuestions.size()!=0) {
String detail = (String) fragmentUserDetails.detailsQuestions.keySet().toArray()[position];
fragmentUserDetails.detailsQuestions.get(detail).add(0,detail);
String[] array = fragmentUserDetails.detailsQuestions.get(detail).toArray(new String[0]);
ArrayAdapter adapter = new ArrayAdapter<String>(fragmentUserDetails.getContext(), R.layout.spinner_item, array){
#Override
public boolean isEnabled(int position) {
if (position == 0) {
return false;
} else {
return true;
}
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
} else {
tv.setTextColor(Color.WHITE);
}
return view;
}};
detailsHolder.questionSp.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_item);
}
}
#Override
public int getItemCount() {
return fragmentUserDetails.detailsQuestions.size();
}
}
Holder:
class DetailsHolder extends RecyclerView.ViewHolder {
Spinner questionSp;
public DetailsHolder(#NonNull View itemView, FragmentUserDetails.OnItemClickListener listener) {
super(itemView);
questionSp = itemView.findViewById(R.id.listrow_question_sp);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onItemClick(pos);
}
});
}
}
details_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true">
<Spinner
android:id="#+id/listrow_question_sp"
android:layout_width="409dp"
android:layout_height="90dp"
android:layout_weight="1"
android:clickable="true"
android:drawablePadding="14dp"
android:focusable="true"
android:maxLines="1"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:spinnerMode="dialog"
android:textSize="18sp"
android:theme="#style/mySpinnerItemStyle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_user_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
android:background="#color/black"
tools:context=".details.FragmentUserDetails">
<ImageView
android:id="#+id/userDetails_img_main"
android:layout_width="306dp"
android:layout_height="160dp"
android:layout_marginTop="30dp"
android:src="#drawable/logo__nobg_2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/homeScr_text_title"
android:layout_width="350dp"
android:layout_height="90dp"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:text="Please enter the following details:"
android:textColor="#color/white"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/userDetails_img_main" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/details_list_rv"
android:layout_width="402dp"
android:layout_height="211dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/homeScr_text_title" />
<com.google.android.material.button.MaterialButton
android:id="#+id/userDetails_next_btn"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginTop="3dp"
android:fontFamily="sans-serif-black"
android:text="NEXT"
android:textSize="20sp"
app:cornerRadius="35dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_ti" />
<com.google.android.material.button.MaterialButton
android:id="#+id/userDetails_btn_back"
style="#style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="88dp"
android:layout_height="50dp"
android:layout_marginTop="3dp"
android:backgroundTint="#color/black"
android:fontFamily="sans-serif"
android:text="BACK"
android:textSize="20sp"
app:cornerRadius="35dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_ti"
app:strokeColor="#color/primeOrng"
app:strokeWidth="1dp" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/details_ti"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif-light"
android:hint="map.."
android:textColorHint="#color/white"
app:layout_constraintTop_toBottomOf="#+id/details_list_rv"
tools:layout_editor_absoluteX="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/listrow_question_et"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_input"
android:drawablePadding="14dp"
android:fontFamily="sans-serif-light"
android:inputType="text"
android:maxLines="1"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/details_ti"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:layout_editor_absoluteX="0dp" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
How can I solve this?
EDIT:
By replacing :
list.getChildCount();
with:
list.getAdapter().getItemCount()
I get the exact size (6) and now I understand it is related to the fact RecycleView recycles the views and not keeping them all, so it will always be a maximum of 3 items(in my example).
now, my question is still how could I achieve my target of saving the selected answers in the spinners by clicking finishBtn(I understand that iterating them is not an option because of the same thing, or maybe there is a way?)

Listview returning the wrong postion with BaseSwipeAdapter

I am using a listview with swipelayout (daimajia library) and my listview is scrolling...
My problem is when I swipe listview item and click on button in it ,it returns me wrong position..
Do you have any idea of how to solve this??
This is my adapter
public View generateView(final int position, final ViewGroup parent) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, null);
SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(getSwipeLayoutResourceId(position));
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
}
});
swipeLayout.setOnDoubleClickListener(new
SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(context, "DoubleClick",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
I think your implementation of getView method is messy. Try this.
ListAdapter Java class.
package com.dev4solutions.myapplication.activities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SimpleSwipeListener;
import com.daimajia.swipe.SwipeLayout;
import com.dev4solutions.myapplication.R;
import java.util.ArrayList;
class ListAdapter extends BaseAdapter {
private ArrayList<String> strings;
private Context mContext;
public ListAdapter(Context context, ArrayList<String> list) {
strings = list;
mContext = context;
}
#Override
public int getCount() {
return strings.size();
}
#Override
public Object getItem(int i) {
return strings.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.ledger_layout, null);
viewHolder = new ViewHolder();
viewHolder.swipeLayout = view.findViewById(R.id.swipe);
viewHolder.textView = view.findViewById(R.id.text_data);
viewHolder.delete = view.findViewById(R.id.delete);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.textView.setText(String.valueOf("Swipe Layout : " + position));
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
Toast.makeText(mContext, "onOpen : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "onDelete Click : " + position,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
// view holder for managing to recycle of view
public static class ViewHolder {
SwipeLayout swipeLayout;
TextView textView;
View delete;
}
}
ledger_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#FF5534"
android:gravity="center"
android:tag="Bottom3"
android:weightSum="10">
<ImageView
android:id="#+id/trash"
android:layout_width="27dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="#android:drawable/ic_delete" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="Delete Item?"
android:textColor="#fff"
android:textSize="17sp" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="4"
android:background="#ffffff"
android:text="Yes,Delete"
android:textColor="#FF5534" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cac6c6"
android:padding="10dp">
<TextView
android:id="#+id/position"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:tag="Hover"
android:text="Do not, for one repulse, forgo the purpose that you resolved to effort. " />
</LinearLayout>
</com.daimajia.swipe.SwipeLayout>
using the way which is marked as an answer will work but there is an another way of doing it too...
adapter class
public class testadapter1 extends RecyclerSwipeAdapter<testadapter1.SimpleViewHolder> {
public static final String TAG = testadapter1.class.getSimpleName();
private static SwipLayoutListener swipLayoutListener;
private static ClickListener clickListener;
String[] time;
Animation animSlide;
boolean ANIM_FLAG = true;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
private int visibleThreshold = 5;
private String phone;
private String email;
public static class SimpleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
SwipeLayout swipeLayout;
TextView text;
TextView info;
TextView swipeImage;
LinearLayout linearLayout;
ImageView imageView;
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
Log.e("position", String.valueOf(getAdapterPosition()));
}
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
text = (TextView) itemView.findViewById(R.id.input_cname);
txtdate = (TextView) itemView.findViewById(R.id.date);
id = (TextView) itemView.findViewById(R.id.input_cid);
Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
FontManager.markAsIconContainer(itemView.findViewById(R.id.swipe), iconFont);
swipeImage = itemView.findViewById(R.id.swipeIcon);
imageView = new ImageView(mContext);
call = (TextView) itemView.findViewById(R.id.call_btn);
sms = (TextView) itemView.findViewById(R.id.sms_btn);
mail = (TextView) itemView.findViewById(R.id.email_btn);
info = (TextView) itemView.findViewById(R.id.detail_btn);
call.setTypeface(iconFont);
sms.setTypeface(iconFont);
mail.setTypeface(iconFont);
info.setTypeface(iconFont);
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, linearLayout);
itemView.setOnClickListener(this);
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
if (swipLayoutListener != null) {
swipLayoutListener.onOpen(layout, getAdapterPosition());
}
}
});
}
}
private static Context mContext;
ArrayList<HashMap<String, String>> mDataset;
public testadapter1(Context mContext, ArrayList<HashMap<String, String>> objects, RecyclerView listView) {
this.mContext = mContext;
this.mDataset = objects;
if (listView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) listView
.getLayoutManager();
listView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView listView,
int dx, int dy) {
super.onScrolled(listView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, parent, false);
return new SimpleViewHolder(view);
}
public interface ClickListener {
void onItemClick(int position, View v);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
viewHolder.txtdate.setText(mDataset.get(position).get("date"));
viewHolder.id.setText("Amount: ₹ " + viewHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// HashMap<String, String> mDataset = getItem1(position);
Intent intent = new Intent(mContext, LedgerDetailActivity.class);
intent.putExtra("ledger_name", String.valueOf(mDataset.get(position).get("ledger_name")));
// Log.e("intent", mDataset.get("ledger_name"));
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
if (mDataset == null) {
Log.d(TAG, "getCount: 0");
return 0;
} else {
Log.d(TAG, "getCount: " + mDataset.size());
return mDataset.size();
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
public void addSwipeListener(SwipLayoutListener swipLayoutListener) {
testadapter1.swipLayoutListener = swipLayoutListener;
}
public interface SwipLayoutListener {
void onOpen(SwipeLayout layout, int position);
}
fragment layout
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/frame3"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/list_ledger"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"/>
<!-- Adding bottom sheet after main content -->
</android.support.v4.widget.SwipeRefreshLayout>
adapter layout
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center"
android:weightSum="7">
<RelativeLayout
android:id="#+id/relativeLayoutSms"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/call_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_phone"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/call_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Call"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutCall"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/sms_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_sms"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sms_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="SMS"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutMail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/email_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_mail"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/email_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Email"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/detail_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_info"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/detail_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Details"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:id="#+id/input_cname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/date"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#id/amount"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#color/colorAccent"
android:textSize="16sp" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/input_cname"
android:layout_marginStart="10dp"
android:paddingTop="2dp"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/input_cid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="2dp"
android:layout_marginStart="10dp"
android:paddingEnd="5dp"
android:textAlignment="viewEnd"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/gp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/input_cid"
android:layout_below="#+id/input_cname"
android:textAlignment="viewEnd"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="14sp"
android:visibility="gone" />
<TextView
android:id="#+id/swipeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#id/gp"
android:layout_marginTop="14dp"
android:paddingStart="6dp"
android:visibility="gone" />
</RelativeLayout>
It's been a long time but I had the same issue. It took hours to solve the problem but the solution is here. This WARNING is from the daimajia's wiki.
ATTENTION: Never bind listeners or fill values in generateView. Just generate the view and do everything else in fillValues (e.g using your holder class) See issues #14 and #17
You can find detailed solution here : Solution to your position problem from daimajia's wiki
And sample code is like this :
//ATTENTION: Never bind listener or fill values in generateView.
// You have to do that in fillValues method.
#Override
public View generateView(int position, ViewGroup parent) {
return LayoutInflater.from(mContext).inflate(R.layout.grid_item, null);
}
#Override
public void fillValues(int position, View convertView) {
TextView t = (TextView)convertView.findViewById(R.id.position);
t.setText((position + 1 )+".");
}
You should do everything in fillValues() function. position value here is always right.
Just follow this rule and everything will be fine with your Swipe ListView.

Recycler View not displaying text properly

I'm trying to implement recycler view in my android app. The data to be shown is got from a server, the data includes a timestamp that should also be displayed.
The code that is setting up the data with the recycler view is as follows:
try{
JSONArray jsonArray = new JSONArray(response);
if(jsonArray.length()!=0) {
TimeStamp = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
TimeStamp[i] = jsonObject.getString("TimeStamp1");
int ij = TimeStamp[i].indexOf('T');
String s = TimeStamp[i].substring(0,ij-1);
String s2 = TimeStamp[i].substring(ij+1,TimeStamp[i].length()-1);
sb.append(s+"\n"+s2+"\n");
String mod = s+"\n"+s2+"\n";
dataset.add(new DataEntryModel(1,mod,10,1));
}
CustomAdapter myAdapter = new CustomAdapter(dataset);
recyclerView.setAdapter(myAdapter);
resultView.setText(sb.toString());
}else{
}
}catch (Exception e){
sb.append(e.toString());
resultView.setText(sb.toString());
}
As you can see from the screenshot for some reason the recycler view is not displaying the full string. I displayed the string in a textview above the button. That seems to be working fine. What is causing the recycler view to not render the items properly. If I try to render s2 first then the time until the the second : is displayed.
The layout for the card :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:clickable="true"
card_view:cardElevation="1dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textBlack"
android:text="UserName"
android:id="#+id/userNametext"
android:layout_alignBaseline="#+id/userName"
android:layout_alignBottom="#+id/userName"
android:layout_alignParentStart="true"
android:layout_marginStart="15dp" />
<TextView
android:text="Loc of userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="75dp"
android:textColor="#color/textBlack"
android:id="#+id/userName"
android:layout_toLeftOf="#+id/userNametext"
android:layout_marginTop="8dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:text="Time Of Entry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Time_of_Entry"
android:layout_marginStart="15dp"
android:textColor="#color/textBlack"
android:layout_below="#+id/textView"
android:layout_alignStart="#+id/textView"
android:layout_marginTop="50dp" />
<TextView
android:text="Loc of Time"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textColor="#color/textBlack"
android:id="#+id/timestamp_of_user"
android:layout_alignBaseline="#+id/Time_of_Entry"
android:layout_alignBottom="#+id/Time_of_Entry"
android:layout_alignStart="#+id/userName"
android:layout_marginStart="14dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
The adapter for the recycler view is
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList<DataEntryModel> dataSet;
CardView cards;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView UserName, TimeStamp;
public MyViewHolder(View itemView){
super(itemView);
this.UserName = (TextView)itemView.findViewById(R.id.userName);
TimeStamp = (TextView)itemView.findViewById(R.id.timestamp_of_user);
cards = (CardView)itemView.findViewById(R.id.card_view);
}
#Override
public void onClick(View view) {
}
}
public CustomAdapter(ArrayList<DataEntryModel> data){
dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_fragment,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView userName = holder.UserName;
TextView TimeStamp = holder.TimeStamp;
userName.setText(SingletonDataClass.SharedPrefsUserNameForSession);
TimeStamp.setText(dataSet.get(position).getTimeStamp());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
What is the reason for this odd behavior of the recycler view? How can I fix this problem?

OnClickListener Recyclerview

my item_layout xml (see it like a template) contain a cardview with some texts and one button, when I run the application. the recyclerview shows two card views with different text (actor names, actors movies) all its ok, but the problem is when I made the button with an onclicklister method to show other activities. the result is when I click on button of the first card view and the button of the second cardview it shows the same result.
what I want is when I click on button on the first cardview it shows Activity number 2, and when I click on the button on the second cardview must shows Activity number 3.
ps: I want different result when I click on button of each cardview
xml :
<RelativeLayout
android:longClickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="7dp">
<ImageView
android:id="#+id/profileImage"
android:layout_width="70dp"
android:layout_height="50dp"
app:civ_border_color="#7f89e9"
android:layout_marginLeft="5dp"
android:background="#drawable/contact1"
android:layout_alignTop="#+id/txtCelebName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginTop="8dp"
android:id="#+id/txtCelebName"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/profileImage"
android:text="Large Text"
android:layout_marginLeft="18dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_marginLeft="18dp"
android:textSize="13dp"
android:id="#+id/txtCelebMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtCelebName"
android:layout_toRightOf="#+id/profileImage"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/textView"
android:layout_marginLeft="10dp"
android:layout_marginTop="27dp"
android:layout_below="#+id/profileImage"
android:text="heur/travaille : 5:00 pm - 8:00 am." />
<TextView
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="emplacement de travaille : cité12 - cité42. "
android:id="#+id/textView2"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="statut : disponible."
android:id="#+id/textView3"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="#+id/textView4"
android:layout_below="#+id/profileImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="...................................."
android:id="#+id/textView5"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4"
android:layout_below="#+id/textView2"
android:layout_marginBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="go"
android:id="#+id/buttonfordialog"
android:layout_alignBottom="#+id/textView4"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3" />
</RelativeLayout>
MainActivity java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ItemAdapter itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
};
final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
collapsingToolbarLayout.setTitle("Alert ! ");
ArrayList<Celebrity> itemList = new ArrayList<>();
fillDummyData(itemList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
itemAdapter = new ItemAdapter(itemList, btnListener);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(itemAdapter);
}
private void fillDummyData(ArrayList<Celebrity> celebList) {
Celebrity celeb1 = new Celebrity();
celeb1.setName("Johny.D");
celeb1.setFamousMovie("Pirates ");
celeb1.setProfilePhotoLocation("#drawable/contact1");
celebList.add(celeb1);
Celebrity celeb2 = new Celebrity();
celeb2.setName("Arnold");
celeb2.setFamousMovie("The Terminator");
celeb2.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTI3MDc4NzUyMV5BMl5BanBnXkFtZTcwMTQyMTc5MQ##._V1._SY209_CR13,0,140,209_.jpg");
celebList.add(celeb2);
}
}
the Adapter :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private List<Celebrity> celebrityList;
private final View.OnClickListener btnListener;
public ItemAdapter(List<Celebrity> celebrityList, View.OnClickListener btnListener) {
this.celebrityList = celebrityList;
this.btnListener = btnListener;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new ItemHolder(itemView, btnListener);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
Celebrity item = celebrityList.get(position);
holder.txtCelebName.setText(item.getName());
holder.txtCelebMovie.setText(item.getFamousMovie());
}
#Override
public int getItemCount() {
return celebrityList.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
private Button buttoncalling;
public TextView txtCelebName, txtCelebMovie;
public ImageView profileImage;
public ItemHolder(View view, View.OnClickListener btnListener) {
super(view);
txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
profileImage = (ImageView) view.findViewById(R.id.profileImage);
buttoncalling = (Button) view.findViewById(R.id.buttonfordialog);
buttoncalling.setOnClickListener(btnListener);
}
}
}
define OnClickListener inside onBindViewHolder();
String [] activities={"FirstActivity","SecondActivity","ThirdActivity"};
String packageNamePrefix="com.example."
//String packageNamePrefix="YOUR_PACKAGE_NAME"
#Override
public void onBindViewHolder(ItemHolder holder,final int position) {
Celebrity item = celebrityList.get(position);
holder.txtCelebName.setText(item.getName());
holder.txtCelebMovie.setText(item.getFamousMovie());
holder.buttoncalling.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new
Intent(MainActivity.this,Class.forName(packageNamePrefix+activities[position]));
startActivity(intent);
}
});
}
it will launch FirstActivity,SecondActivity,ThirdActivity respectively.
I hope it will help.
There are many ways to implement OnClickListener inside RecyclerView adapter.
You can implement click listener inside onBindViewHolder() method like below
holder.buttoncalling.setOnClickListener(new View.OnClickListener(){
// perform click operation
});
You can also implement it inside you ItemHolder like this
buttoncalling.setOnClickListener( new View.OnClickListener(){
// perform click operation
});
and use getAdapterPosition() whenever you need item clicked position as recommended in official docs.
You can also make interface callbacks to your Activity and pass position along with it for refrence.
You should use inline onclickListener like below;
YOURBUTTON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your codes goes here...
}
});

How to close an expanded list item on second click if it's expanded?

I have a recycler view. I have added an expandable view in the list item view. On a click it expands and show the layout. But now I want to close it on click of same item if its open.
Now if I click on 1st item the layout gets expanded and then if i click on 2nd item layout for 2nd item gets expanded and layout for 1st item gets closed.
I have followed this link :
RecyclerView expand/collapse items
Adapter:
public class BookingsAdapter extends RecyclerView.Adapter<BookingsAdapter.MyViewHolder> implements View.OnClickListener{
private int expandedPosition = -1;
private List<Bookings> bookingsList;
int status;
Context context;
public interface OnItemClickListener {
void onItemClick(Events item);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView eventName,eventType,eventDateTime,userName;
public RelativeLayout expandLayout;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
eventName = (TextView) view.findViewById(R.id.text_eventName);
eventType = (TextView) view.findViewById(R.id.textView_EventType);
eventDateTime = (TextView) view.findViewById(R.id.text_dateTime);
userName = (TextView) view.findViewById(R.id.text_userName);
expandLayout = (RelativeLayout) view.findViewById(R.id.expandLayout);
cardView = (CardView) view.findViewById(R.id.card_view);
}
}
public BookingsAdapter(ArrayList<Bookings> bookingsList,Context context) {
this.bookingsList = bookingsList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.bookings_card, parent, false);
MyViewHolder holder = new MyViewHolder(itemView);
// Sets the click adapter for the entire cell
// to the one in this class.
holder.itemView.setOnClickListener(BookingsAdapter.this);
holder.itemView.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bookings bookings = bookingsList.get(position);
holder.eventName.setText(bookings.getEventName());
holder.eventType.setText(bookings.getEventType());
holder.eventDateTime.setText(bookings.getEventDateTime());
holder.userName.setText(bookings.getUserName());
if (position == expandedPosition) {
holder.expandLayout.setVisibility(View.VISIBLE);
} else {
holder.expandLayout.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
MyViewHolder holder = (MyViewHolder) view.getTag();
Bookings bookingsItem = bookingsList.get(holder.getPosition());
// Check for an expanded view, collapse if you find one
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
// Set the current position to "expanded"
expandedPosition = holder.getPosition();
notifyItemChanged(expandedPosition);
Toast.makeText(context, "Clicked: "+ bookingsItem.getEventName(), Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return bookingsList.size();
}
}
Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#android:color/white"
android:layout_marginTop="05dp"
android:layout_marginRight="05dp"
android:layout_marginLeft="05dp"
card_view:cardElevation="2dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/parentLayout">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="90dp"
android:id="#+id/detailsLayout">
<RelativeLayout
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="05dp"
android:layout_marginBottom="05dp"
android:id="#+id/eventLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event name"
android:id="#+id/text_eventName"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="14sp"
android:textColor="#android:color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="("
android:id="#+id/textView26"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/textView_EventType"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date and time"
android:id="#+id/text_dateTime"
android:layout_below="#+id/textView26"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="05dp"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event type"
android:id="#+id/textView_EventType"
android:layout_below="#+id/text_eventName"
android:layout_toRightOf="#+id/textView26"
android:layout_toEndOf="#+id/textView26"
android:layout_marginTop="05dp"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=")"
android:id="#+id/textView29"
android:layout_alignTop="#+id/textView_EventType"
android:layout_toRightOf="#+id/textView_EventType"
android:layout_toEndOf="#+id/textView_EventType"
android:textSize="12sp"
android:textColor="#color/colorAccent" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/place_autocomplete_separator"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:layout_alignParentTop="true">
</View>
</RelativeLayout>
<View
android:layout_width="3dp"
android:layout_height="wrap_content"
android:background="#color/grey">
</View>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/eventLayout"
android:layout_toRightOf="#+id/eventLayout"
android:layout_toEndOf="#+id/eventLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/eventLayout"
android:id="#+id/profilepicLayout">
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:src="#drawable/ic_person_black_48dp"
android:id="#+id/profileImage"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="false"
android:background="#drawable/circle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:id="#+id/text_userName"
android:layout_below="#+id/profileImage"
android:layout_marginTop="05dp"
android:textColor="#android:color/black"
android:textSize="12sp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textAlignment="center" />
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:layout_below="#+id/detailsLayout"
android:id="#+id/expandLayout"
android:visibility="gone">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/place_autocomplete_separator"></View>
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:id="#+id/imageView12"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#drawable/ic_call_black_18dp"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="05dp"
android:layout_marginBottom="05dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:id="#+id/imageView13"
android:layout_alignTop="#+id/imageView12"
android:layout_centerHorizontal="true"
android:background="#drawable/ic_textsms_black_18dp" />
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:id="#+id/imageView14"
android:layout_alignParentBottom="false"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp"
android:background="#drawable/ic_chat_black_18dp"
android:layout_centerVertical="true"
android:layout_alignTop="#+id/imageView13" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
EDIT: I have added boolean variable in class and did this. Noting happens. Layout dose not get close when I click on item
#Override
public void onClick(View view) {
MyViewHolder holder = (MyViewHolder) view.getTag();
Bookings bookingsItem = bookingsList.get(holder.getPosition());
// Check for an expanded view, collapse if you find one
// set previously expanded row to false
for(int i=0;i<bookingsList.size();i++)
{
if(bookingsList.get(i).expanded)
{
bookingsList.get(i).expanded = false;
}
}
//set current item expanded
bookingsList.get(holder.getPosition()).expanded = true;
if (expandedPosition >= 0) {
int prev = expandedPosition;
notifyItemChanged(prev);
}
// Set the current position to "expanded"
expandedPosition = holder.getPosition();
notifyItemChanged(expandedPosition);
Toast.makeText(context, "Clicked: "+ bookingsItem.getEventName(), Toast.LENGTH_SHORT).show();
}
Now I want to close the expanded layout of same item on click of item.
NOTE: Take a boolean variable named expanded in class Bookings and by default save it as false where you are adding values to your list then in your on click do something like this
public class BookingsAdapter extends RecyclerView.Adapter<BookingsAdapter.MyViewHolder> implements View.OnClickListener{
private List<Bookings> bookingsList;
int status;
Context context;
public interface OnItemClickListener {
void onItemClick(Events item);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView eventName,eventType,eventDateTime,userName;
public RelativeLayout expandLayout;
public CardView cardView;
public MyViewHolder(View view) {
super(view);
eventName = (TextView) view.findViewById(R.id.text_eventName);
eventType = (TextView) view.findViewById(R.id.textView_EventType);
eventDateTime = (TextView) view.findViewById(R.id.text_dateTime);
userName = (TextView) view.findViewById(R.id.text_userName);
expandLayout = (RelativeLayout) view.findViewById(R.id.expandLayout);
cardView = (CardView) view.findViewById(R.id.card_view);
}
}
public BookingsAdapter(ArrayList<Bookings> bookingsList,Context context) {
this.bookingsList = bookingsList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.bookings_card, parent, false);
MyViewHolder holder = new MyViewHolder(itemView);
// Sets the click adapter for the entire cell
// to the one in this class.
holder.itemView.setOnClickListener(BookingsAdapter.this);
holder.itemView.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bookings bookings = bookingsList.get(position);
holder.eventName.setText(bookings.getEventName());
holder.eventType.setText(bookings.getEventType());
holder.eventDateTime.setText(bookings.getEventDateTime());
holder.userName.setText(bookings.getUserName());
if (bookings.expanded) {
holder.expandLayout.setVisibility(View.VISIBLE);
} else {
holder.expandLayout.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
MyViewHolder holder = (MyViewHolder) view.getTag();
if(bookingsList.get(holder.getPosition()).expandad)
{
bookingsList.get(holder.getPosition()).expandad=false;
notifyDataSetChanged();
}
else{
// set previously expanded row to false
for(int i=0;i<bookingsList.size();i++)
{
if(bookingsList.get(i).expanded)
{
bookingsList.get(i).expandad=false;
}
}
//set current item expanded
bookingsList.get(holder.getPosition()).expandad=true;
notifyDataSetChanged();
}
Toast.makeText(context, "Clicked: "+ bookingsItem.getEventName(), Toast.LENGTH_SHORT).show();
}

Categories

Resources