In my MainActivity.java I have a sort of button to login. I also have 4 fragments, each of them containing a recycler view (imageview + textview).
The imageview is hidden, but when I press the button it becomes visibile. How can I do that? The notifyDataSetChanged() doesn't work in the adapter and I can't call it on the adapter in the fragment page, because is outside the onCreateView method.
Here's my code:
MainActivity: contains the button
Fragment Page:
public class Classici_Tab extends Fragment {
LinkedList<Book> catalog = new LinkedList<>();
RecyclerView mRecyclerView;
BookListAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.classici_tab, container, false);
fillCatalog("catalog.csv"); //fill the LinkedList
mRecyclerView = (RecyclerView) fragmentView.findViewById(R.id.classici_rv);
mAdapter = new BookListAdapter(getContext(), catalog);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return fragmentView;
}
}
Adapter:
public class BookListAdapter extends RecyclerView.Adapter<BookListAdapter.BookViewHolder> {
// View Holder
class BookViewHolder extends RecyclerView.ViewHolder
{
public final ImageView cover;
public final TextView title;
public final TextView author;
public final ImageView availability;
final BookListAdapter mAdapter;
public BookViewHolder(View itemView, BookListAdapter adapter) {
super(itemView);
cover = (ImageView) itemView.findViewById(R.id.cover);
title = (TextView) itemView.findViewById(R.id.title);
author = (TextView) itemView.findViewById(R.id.author);
availability = (ImageView) itemView.findViewById(R.id.availability);
MainActivity m = new MainActivity();
if(m.loggedin) availability.setVisibility(View.VISIBLE);
else availability.setVisibility(View.INVISIBLE);
this.mAdapter = adapter;
}
}
private LinkedList<Book> mBookList = new LinkedList<>();
private LayoutInflater mInflater;
boolean isVisible = false;
public BookListAdapter() {}
public BookListAdapter(Context context, LinkedList<Book> bookList) {
mInflater = LayoutInflater.from(context);
this.mBookList = bookList;
}
//IT DOESN'T WORK
public void setPicturesVisibility(boolean isVisible){
this.isVisible = true;
notifyDataSetChanged();
}
#Override
public BookViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.tab_list_item, parent, false);
return new BookViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(BookViewHolder holder, int position) {
holder.cover.setImageResource(mBookList.get(position).getCover());
holder.title.setText(mBookList.get(position).getTitle());
holder.author.setText(mBookList.get(position).getAuthor());
holder.availability.setImageResource(mBookList.get(position).getAvailability());
if(isVisible){
holder.availability.setVisibility(View.VISIBLE);
}else{
holder.availability.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return mBookList.size();
}
}
Not sure why you need to recreate adapter. Without recreating adapter, you can add listener to the button and in the onclick event handler, make image visible in recyclerview adapter's viewholder constructor.
public ViewHolder(View view) {
super(view);
textview = view.findViewById(R.id.textview);
imgView = view.findViewById(R.id.storeImg);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgView.setVisibility(View.VISIBLE);
}
});
}
You can find recyclerview examples here http://www.zoftino.com/android
There is no need to recreate adapter. You can add a boolean arePicturesVisible = false; in your RecyclerViewAdapter.
And make a method in adapter:
public void setPicturesVisibility(boolean areVisible){
arePicturesVisible = areVisible;
notifyDataSetChanged();
}
Then add:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
.....
if(arePicturesVisible){
holder.image.setVisibility(View.VISIBLE);
}else{
holder.image.setVisibility(View.INVISIBLE);
}
.....
}
Then in your button onClick() method call setPicturesVisibility() from RecyclerView adapter.
Related
I'm trying to start a new Fragment that shows the details of the item that was clicked on in the RecyclerView. The RecyclerView is on a Fragments. I've tried this in Activities and it worked perfectly but I'm trying to convert it to use on Fragments. And Also, how to detect other gestures in the RecyclerView (swipe, etc...)
My Adapter :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private final ArrayList<Tip> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewType;
//TextView textViewDetail;
ImageView imageViewImage;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewTitle = itemView.findViewById(R.id.title);
this.textViewType = itemView.findViewById(R.id.type);
//this.textViewDetail = itemView.findViewById(R.id.detail);
this.imageViewImage = itemView.findViewById(R.id.itemImage);
}
}
public MyAdapter(ArrayList<Tip> data) {
this.dataSet = data;
}
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate( R.layout.item, parent, false);
view.setOnClickListener(HomeFragment.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int listPosition) {
TextView textViewTitle = holder.textViewTitle;
TextView textViewType = holder.textViewType;
//TextView textViewDetail = holder.textViewDetail;
ImageView imageViewImage = holder.imageViewImage;
textViewTitle.setText( dataSet.get(listPosition).getTitle() );
textViewType.setText( dataSet.get(listPosition).getType() );
//textViewDetail.setText( dataSet.get(listPosition).getDetail() );
imageViewImage.setImageResource( dataSet.get(listPosition).getImage() );
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
My Fragment :
public class HomeFragment extends Fragment {
public static RecyclerView.Adapter myAdapter;
private static RecyclerView.LayoutManager myLayoutManager;
private static RecyclerView myRecyclerView;
public static View.OnClickListener myOnClickListener;
private static ArrayList<Tip> myData;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Get the integer from the integers.xml resource file
Resources res = getResources();
int gridColumnCount = res.getInteger(R.integer.grid_column_count);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
// Add the following lines to create RecyclerView
myRecyclerView = view.findViewById(R.id.my_recycler_view);
myRecyclerView.setHasFixedSize(true);
//myLayoutManager = new LinearLayoutManager( view.getContext() );
myLayoutManager = new GridLayoutManager( view.getContext(),gridColumnCount );
myRecyclerView.setLayoutManager( myLayoutManager );
myRecyclerView.setItemAnimator( new DefaultItemAnimator() );
myData = new ArrayList<Tip>();
for (int i = 0; i < MyData.tipTitleArray.length; i++) {
myData.add(new Tip( MyData.tipTitleArray[i], MyData.tipTypeArray[i], MyData.tipDetailArray[i], MyData.id_[i], MyData.tipImageArray[i] ));
}
myAdapter = new MyAdapter(myData);
myRecyclerView.setAdapter(myAdapter);
//On retourne la View
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
fr.cnam.smb116.mimi_tips_navdraw.databinding.FragmentHomeBinding binding = null;
}
}
Don't use static listener and recyclerview instance.
Better to add callBack function to handle this.
e.g
interface RecyclerViewItemClickListener<T> {
void onClick(int position, T data);
}
init property in your adapter
RecyclerViewItemClickListener<Tip> listener
constructor of your Adapter
MyAdapter(RecyclerViewItemClickListener<Tip> listener) {
this. listener = listener
}
in
onBindViewHolder() {
holder.setOnClickListener(v -> {
listener.onClick(position, dataSet.get(listPosition));
})
}
In Your Fragment
Implement this interface
public class HomeFragment extends Fragment implements RecyclerViewItemClickListener<Tip> {
}
your adapter instance
myAdapter = new MyAdapter(myData,this);
implement onClick Method in your fragment
void onClick(int position, Tip tip){
// your listener
}
I have a RecyclerView with multiple TextViews and a Button. The button triggers an animation like the gif below:
I am doing this by creating a RecyclerView.Adapter and creating an OnClickListener like so:
public class recyclerViewAdapter extends RecyclerView.Adapter<recyclerViewAdapter.ViewHolder> {
private ArrayList<MyObject> objects;
// constructor and other stuff ...
public void setDefaultRequestBtnClickListener(View.OnClickListener defaultRequestBtnClickListener) {
this.defaultRequestBtnClickListener = defaultRequestBtnClickListener;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
MyObject object = objects.get(position);
if (object.getRequestBtnClickListener() != null) {
holder.Btn.setOnClickListener(object.getRequestBtnClickListener());
}else {
holder.Btn.setOnClickListener(defaultRequestBtnClickListener);
}
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView value;
TextView currentVal;
TextView Btn;
ConstraintLayout parent;
public ViewHolder(#NonNull View itemView) {
super(itemView);
value = itemView.findViewById(R.id.totalPrice);
currentVal = itemView.findViewById(R.id.checkBtn);
Btn = itemView.findViewById(R.id.animateBtn);
parent = itemView.findViewById(R.id.parent);
}
public void bind(final OnMyClickListener listener) {
parent.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onMyClick(v, getLayoutPosition());
}
});
}
}
public interface OnMyClickListener{
void onMyClick(View view, int position);
}
}
this creates and binds a viewholder in a recyclerview to the TextViews and buttons. At the moment a user has to click the element to activate the Btn and animation. The below is the Fragment that is initiating the adapter:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.frag_object_layout, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.list);
final ArrayList<MyObject> objects = MyObject.getTestingList();
final recyclerViewAdapter adapter = new recyclerViewAdapter(objects, getContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter.setDefaultRequestBtnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
recyclerViewAdapter.ViewHolder holder = (recyclerViewAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(Position);
if (holder != null) {
if (holder.value.getAlpha() == 0.0f) {
holder.value.animate().alpha(1.0f).setDuration(500);
holder.value.animate().translationY(-38).setDuration(1000);
holder.checkValue.animate().translationY(38).setDuration(1000);
} else {
holder.value.animate().alpha(0.0f).setDuration(500);
holder.value.animate().translationY(0).setDuration(500);
holder.checkValue.animate().translationY(0).setDuration(500);
}
}
}
});
adapter.setOnMyClickListener(new recyclerViewAdapter.OnMyClickListener() {
#Override
public void onMyClick(View view, int pos) {
Position = pos;
holder = (recyclerViewAdapter.ViewHolder) recyclerView.findViewHolderForAdapterPosition(Position);
}
});
return rootView;
}
}
This is all working great on an emulator, but on an older device the animation is skipping and the views go directly to their final position. Why is that? I checked the processing time and it is below the 16ms threshold.
How can I improve this?
(Posting the whole code is difficult here. ask for code and I will update the question)
I have two tabs (fragments), NewOrders and FinishedOrders, I'm populating the orders via Volley requests, now each item inside the New Orders tab has a SwipeLayout which show a clickable textview that makes the order finished, and move it to the other tab (backend stuff..), and I got this working perfectly,
The problem is when I click to finish, the recyclerview isn't updated once the request sent successfully, I have to do pull-to-refresh so it would update..! it seems easy to solve, but the issue is handling the swipelayout listener done inside onBindView method inside the adapter..!! that's only place to access it according to the library I'm using (I guess)..! on the other hand refreshing and populating the list happens in the NewOrder tab fragment..!
So how can I make the item to be removed from the list after the click and becomes updated..?!
Any thoughts..!?
My Adapter Class + ViewHolder
Note: the implemented methods in the adapter are required because of the interface of SwipeLayout library
public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
implements SwipeAdapterInterface, SwipeItemMangerInterface {
protected SwipeItemRecyclerMangerImpl mItemManger = new SwipeItemRecyclerMangerImpl(this);
public Context context;
ArrayList<OrderPresenter> orders;
public OrdersDataAdapter(ArrayList<OrderPresenter> orders, Context context) {
this.orders = orders;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);
return new NewOrderVH(v);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final OrderPresenter order = this.orders.get(position);
final NewOrderVH vh1 = (NewOrderVH) holder;
vh1.setData(orders.get(position));
mItemManger.bindView(vh1.itemView, position);
vh1.swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
vh1.swipeLayout.addDrag(SwipeLayout.DragEdge.Left,
vh1.swipeLayout.findViewById(R.id.bottom_wrapper));
if (order.isFinished()) {
vh1.swipeLayout.setSwipeEnabled(false);
vh1.setBadge("DONE");
vh1.setBadgeColor(order.getBadgeColor());
} else {
vh1.finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get the clicked item position?
final int position = vh1.getAdapterPosition();
// these responsible for the request which make the order finished
OrderPresenter order = orders.get(position);
OrderRepository.setOrderFinURL(order.getID());
OrderRepository.FinishOrder(order.getID(), context);
/*the commented three lines below didn't help with the problem*/
// notifyItemChanged(position);
// notifyItemRemoved(position);
// notifyDataSetChanged();*/
order.setStatus(order.getStatusText(Order.FINISHED));
}
});
}
}
#Override
public int getItemCount() {
return orders.size();
}
public class NewOrderVH extends RecyclerView.ViewHolder {
SwipeLayout swipeLayout;
private TextView finish;
private CardView orderCard;
TextView Badge;
private ImageView cusPic;
private TextView cusName;
private TextView CusAdress;
private TextView vendorsNum;
private TextView itemsNum;
private TextView time;
private TextView emptyView;
public NewOrderVH(View itemView) {
super(itemView);
Badge = (TextView) itemView.findViewById(R.id.badge);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
finish = (TextView) itemView.findViewById(R.id.finish);
orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
cusName = (TextView) itemView.findViewById(R.id.cusName);
CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
time = (TextView) itemView.findViewById(R.id.time);
emptyView = (TextView) itemView.findViewById(R.id.empty_view);
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), OrderDetails.class);
v.getContext().startActivity(intent);
}
});
}
public void setData(final OrderPresenter data) {
time.setText(data.getOrderTime());
cusName.setText(data.getFullName());
vendorsNum.setText(data.getVendorsCount());
itemsNum.setText(data.getItemsCount());
CusAdress.setText(data.getFullAddress());
Picasso.with(context).load(data.getCustomerPicture()).into(cusPic);
}
public void setBadgeColor(int drawable) {
this.Badge.setBackgroundResource(drawable);
}
public void setBadge(String badge) {
this.Badge.setText(badge);
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
#Override
public void openItem(int position) {
}
#Override
public void closeItem(int position) {
}
#Override
public void closeAllExcept(SwipeLayout layout) {
}
#Override
public void closeAllItems() {
}
#Override
public List<Integer> getOpenItems() {
return null;
}
#Override
public List<SwipeLayout> getOpenLayouts() {
return null;
}
#Override
public void removeShownLayouts(SwipeLayout layout) {
}
#Override
public boolean isOpen(int position) {
return false;
}
#Override
public Attributes.Mode getMode() {
return null;
}
#Override
public void setMode(Attributes.Mode mode) {
}
}
My NewOrder Fragment
Note: the FinishedOrders tab (fragment) does the same thing as new order but filters the current the Finished status.
public class NewOrdersTab extends Fragment {
RecyclerView recyclerView;
OrdersDataAdapter adapter;
private SwipeRefreshLayout swiperefresh;
private TextView emptyView;
ArrayList<OrderPresenter> modelData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.new_orders_tab_frag, container, false);
modelData = new ArrayList<>();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
swiperefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
swiperefresh.setColorSchemeResources(R.color.colorPrimary, R.color.color_error, R.color.colorInfo);
adapter = new OrdersDataAdapter(modelData, getActivity());
emptyView = (TextView) rootView.findViewById(R.id.empty_view);
recyclerView.setAdapter(adapter);
adapter.setMode(Attributes.Mode.Single);
OrderRepository.fetchOrders("awaiting-shipment", getActivity(), new DataFetch() {
#Override
public void onResponse(ArrayList<OrderPresenter> data) {
swiperefresh.setRefreshing(true);
if (data.size() != 0) {
swiperefresh.setRefreshing(true);
emptyView.setVisibility(View.GONE);
modelData.clear();
modelData.addAll(data);
adapter.notifyDataSetChanged();
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.No_New_Orders));
}
swiperefresh.setRefreshing(false);
}
});
return rootView;
}
}
I figured it out, I just added these two lines after I make the request..!
orders.remove(position);
notifyItemRemoved(position);
//notifyDataSetChanged(position);
So I have a CardView in a RecyclerView which has some data inside it. I would like to click on a specific card and launch a new fragment that displays specific data from the data in the CardView (more details about the data in the CardView). Here is the relevant code.
I don't have the most experience in programming and Android in general, any help would be appreciated!
DetailsFragment: `
public class DetailsFragment extends Fragment {
private CardView cardView;
private RecyclerView rv;
private List<Detail> detailList = new ArrayList<>();
public DetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
Context context = getActivity();
cardView = (CardView) rootView.findViewById(R.id.cv);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(context);
rv.setLayoutManager(llm);
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData() {
detailList = new ArrayList<>();
// not sure here
detailList.add(new Detail(" "));
}
private void initializeAdapter(){
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
}
}
RVNewsAdapater:
public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.NewsViewHolder> {
public static final String KEY_LINK ="link";
public static class NewsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String TAG = "Hello";
CardView cv;
TextView date;
TextView link;
TextView title;
TextView today;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
date = (TextView) itemView.findViewById(R.id.date);
link = (TextView) itemView.findViewById(R.id.link);
title = (TextView) itemView.findViewById(R.id.heading);
today = (TextView) itemView.findViewById(R.id.today);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = null;
for(int postion = 0; postion<42; postion++) {
intent = new Intent(context, Details.class);
}
context.startActivity(intent);
}
}
List<News> news;
RVNewsAdapter(List<News> news) {
this.news = news;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVNewsAdapter.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
NewsViewHolder nvh = new NewsViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NewsViewHolder newsViewHolder, int i) {
newsViewHolder.date.setText(news.get(i).date);
newsViewHolder.link.setText(news.get(i).link);
newsViewHolder.title.setText(news.get(i).title);
newsViewHolder.today.setText(news.get(i).today);
}
#Override
public int getItemCount() {
if (news != null) {
return news.size();
}
return 0;
}
}
RVDetailAdapter:
public class RVDetailAdapter extends RecyclerView.Adapter<RVDetailAdapter.DetailViewHolder> {
public static class DetailViewHolder extends RecyclerView.ViewHolder {
TextView link;
public DetailViewHolder(View itemView) {
super(itemView);
link = (TextView) itemView.findViewById(R.id.link);
}
}
List<Detail> detail;
RVDetailAdapter(List<Detail> detail) {
this.detail = detail;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVDetailAdapter.DetailViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
DetailViewHolder dvh = new DetailViewHolder(v);
return dvh;
}
#Override
public void onBindViewHolder(DetailViewHolder detailViewHolder, int i) {
detailViewHolder.link.setText(detail.get(i).link);
}
#Override
public int getItemCount() {
if (detail != null) {
return detail.size();
}
return 0;
}
}
Not sure if you're still looking for an answer, but I just saw the post and thought I'd give you one option.
When I'm using a RecyclerView (doesn't matter if it's using the CardView or not, it's the same for any list item), I create a a click listener for the view item in the Adapter. When the user clicks the item/cardview, I dispatch an item click event. It's your choice on how you respond - you can use a standard callback interface (and pass in your listener when you create the adapter) or use something like EventBus.
Here's an example of the code you would add to your adapter class:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemClick(view);
}
});
return new ViewHolder(view);
}
private void itemClick(View view) {
//Handle item event here
//EventBus.getDefault().post(new ItemSelectedEvent(/*send apprpopriate data*/));
}
I have one android fragment that have a listView. Now I want implement onItemClickListener and show a Modal, if the user click on one item of ListView. Then, if I click on one items, I should to see a Modal with another listView. So with my code, if I try to click on one items, I can display the items of the last element of my principal listView, and it is not good.
This is my Fragment:
public class AlertsFragment extends Fragment {
private AlertAdapter pAdapter;
AlertXAgentAdapter agentAdapter;
AlertXReactionAdapter reactionAdapter;
private RecyclerView recyclerView,recyclerAgentView,recyclerReactionView;
private List<Alert> lista= new ArrayList<Alert>();
View v;
ExpandableListView expandableListView;
ExpandableListAdapter expandableListAdapter;
private static final int ARG_SECTION_NUMBER =6;
#Override
public void onAttach(Context context) {
super.onAttach(context);
((AndroidNavDrawerActivity) context).onSectionAttached(
ARG_SECTION_NUMBER);
}
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
v=inflater.inflate(R.layout.alerts_activity, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
//recupero la lista delle medication
AlertDAO manager = new AlertDAO(this.getContext());
lista = manager.getAlerts();
pAdapter = new AlertAdapter(lista, new AlertAdapter.OnItemClickListener() {
#Override
public void onItemClick(Alert item) {
try{
final Dialog dialog = new Dialog(v.getContext());
LayoutInflater inflater = LayoutInflater.from(v.getContext());
View dialogView = inflater.inflate(R.layout.alert_agent_reaction_modal, null);
//agent
recyclerAgentView = (RecyclerView) dialogView.findViewById(R.id.recycler_agent_view);
//reaction
recyclerReactionView = (RecyclerView) dialogView.findViewById(R.id.recycler_reaction_view);
dialog.setContentView(dialogView);
dialog.setTitle("Agent and Reaction");
//agent
agentAdapter = new AlertXAgentAdapter(item.getListaAgent());
//reaction
reactionAdapter = new AlertXReactionAdapter(item.getListaReaction());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(v.getContext());
recyclerAgentView.setLayoutManager(mLayoutManager);
recyclerAgentView.setItemAnimator(new DefaultItemAnimator());
recyclerAgentView.setAdapter(agentAdapter);
RecyclerView.LayoutManager mLayoutManager2 = new LinearLayoutManager(v.getContext());
recyclerReactionView.setLayoutManager(mLayoutManager2);
recyclerReactionView.setItemAnimator(new DefaultItemAnimator());
recyclerReactionView.setAdapter(reactionAdapter);
dialog.show();
}catch(Exception e){
Log.e("","");
}
}
});
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(v.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(pAdapter);
/**
* Inflate the layout for this fragment
*/
return v;
}
}
This is my Adapter
public class AlertAdapter extends RecyclerView.Adapter<AlertAdapter.MyViewHolder> {
private List<Alert> list;
public Alert alert;
public OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(Alert item);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView startDate, endDate,description,status;
public MyViewHolder(View view) {
super(view);
startDate = (TextView) view.findViewById(R.id.startDate);
endDate = (TextView) view.findViewById(R.id.endDate);
description = (TextView) view.findViewById(R.id.description);
status = (TextView) view.findViewById(R.id.status);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(listener != null){
listener.onItemClick(alert);
}
}
}
public AlertAdapter(List<Alert> list,OnItemClickListener listener) {
this.list = list;
this.listener=listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.alert_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
alert = list.get(position);
holder.startDate.setText(alert.getDateStart()!=null ? alert.getDateStart() : "");
holder.endDate.setText(alert.getDateEnd()!=null ? alert.getDateEnd() : "");
holder.description.setText(alert.getAlertInfo().getDisplayName());
//holder.type.setText(planOfCare.getDateEnd()!=null ? planOfCare.getDateEnd() : "");
holder.status.setText(alert.getAlarmAlertInfo().getDisplayName());
}
#Override
public int getItemCount() {
return list.size();
}
}
Your Alert variable is not getting assigned to proper object as you are assigning it in onBindViewHolder method. In your ViewHolder's onclick method try using this instead of passing the Alert variable
listener.onItemClick(list.get(this.getAdapterPosition()));
I think you should do something like this
public class AlertsFragment extends Fragment implements OnClickListener {
personRewardAdapter =new PersonRewardAdapter(PersonRewardSelectionActivity.this, Utilities.R_entities);
rewardList.setAdapter(personRewardAdapter);
rewardList.setOnclickListener(getActivity());
}
public void OnClick(){
}
do this in onCreateView. I am doing this in my code and maybe It helps you, so i am sharing to you