Recyclerview change item color outside adapter - java

Currently I'm trying figure out how to change an RecyclerView item color outside adapter. I'm just manipulating the position, and works fine! But I must swipe the page to color update, and I don't know what I should do to fix this problem.
Check my code:
MainActivity.java
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
player_prev = findViewById(R.id.prev);
player_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((currentPos-1) > 0) {
killMediaPlayer();
initAudio(getApplicationContext(),
RecyclerViewAdapter.mData.get(currentPos - 1).getURL());
currentPos -= 1;
RecyclerViewAdapter.OldselectedPos = RecyclerViewAdapter.selectedPos;
RecyclerViewAdapter.selectedPos = currentPos;
adapter.notifyDataSetChanged();
}
});
...
}
RecyclerViewAdapter.java
package etes.xdda.music;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
MainActivity activity;
static List<mList> mData;
Dialog myDialog;
public static int selectedPos = RecyclerView.NO_POSITION;
public static int OldselectedPos = RecyclerView.NO_POSITION;
private LinearLayout menu_dialog, menu_dialog2;
public static TextView song_detail;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
#Override
public void onClick(View view) { }
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(activity).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(activity);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
OldselectedPos = selectedPos;
selectedPos = vHolder.getAdapterPosition();
notifyItemChanged(selectedPos);
notifyItemChanged(OldselectedPos);
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
menu_dialog2 = v.getRootView().findViewById(R.id.menu_dialog2);
menu_dialog2.setVisibility(v.VISIBLE);
song_detail = v.getRootView().findViewById(R.id.song_detail);
song_detail.setVisibility(v.VISIBLE);
String newName;
newName = mData.get(vHolder.getAdapterPosition()).getName();
if (newName.length() > 42) {
newName = newName.substring(0, 38) + "...";
}
song_detail.setText(newName);
activity.killMediaPlayer();
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,205);
activity.updateNotificationBar("mzPlay", mData.get(vHolder.getAdapterPosition()).getName());
MainActivity.currentPos = vHolder.getAdapterPosition();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
//Toast.makeText(activity, String.valueOf(holder), Toast.LENGTH_LONG).show();
if(selectedPos == position){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = itemView.findViewById(R.id.name_list);
tv_author = itemView.findViewById(R.id.author_list);
img = itemView.findViewById(R.id.img_music);
}
}
}
Video: https://ntcdn.stream/20181009_2342010.mp4
The problem is: I must swipe the page to item colors be updated, how can I update the colors without page swipe?

Storing andoid classes in static variables is really a very bad practice. You should interact with your adapter the regular way, using a non static field, for example:
//This will go in your onCreate() for example
MyAdapter adapter = new MyAdapter(parameters);
...
adapter.highligtedItemPosition = 10;
adapter.notifyItemChanged(10);
and later in your onBindViewHolder() react according to what background you want set:
if(position == highligtedItemPosition ){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
in this example you must add an integer field:
int highligtedItemPosition;
to your adapter to store the position of the item you want to change the color of.
UPDATE:
You are not calling notifyItemChange() or notifyDataSetChanged() from your activity, so the adapter needs to "wait" for the scrolling action to "see" the changes. You should call notifyItemChange() or notifyDataSetChanged() from your player_prev's OnClickListener instead. So the adapter will reflect the changes immediately.

Related

Click on one card view affected another card view value

When I create a custom card view in recycler view and click the increment button counter work properply. But when I crete another cardview then already created card counter value reset to 0. How to solve this issue?
Here's my Main Activity code
package com.example.muhasbaapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.example.muhasbaapp.CustomAdapter.ViewHolder.*;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter mAdapter,countAdapter;
private RecyclerView.LayoutManager layoutManager,layoutManager2;
private static RecyclerView recyclerView,recyclerView2;
private ImageView imageView;
public CustomModel customModel;
public static ArrayList<String> input = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView2=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView2.setHasFixedSize(true);
layoutManager2=new LinearLayoutManager(this);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
mAdapter= new CustomAdapter(input);
recyclerView2.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { //add action2 kau kat sini
switch (item.getItemId()) {
case R.id.action_item_1:
openCustomDialoge();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openCustomDialoge() {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.user_generated_cards, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s=editText.getText().toString();
if (s.isEmpty()){
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
}else {
input.add(s);
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.show();
}
}
And Here' my Adaptar Class code
package com.example.muhasbaapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public ArrayList<String> values;
final CustomModel customMdl=new CustomModel();
final MainActivity mainActivity=new MainActivity();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tv;
public View layout;
public TextView counter_value;
public ImageView increment,decrement, deleted;
public int counter;
public ViewHolder(View v) {
super(v);
layout = v;
tv = (TextView) v.findViewById(R.id.textViewName);
counter_value=(TextView) v.findViewById(R.id.counter);
increment=(ImageView)v.findViewById(R.id.increment);
decrement=(ImageView)v.findViewById(R.id.decrement);
deleted=(ImageView)v.findViewById(R.id.delbtn);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(ArrayList<String> myDataset) {
this.values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.custom_cards_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.tv.setText(name);
final int[] counter={0};
holder.deleted.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
}
});
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter[0] == 0) {
Toast.makeText(v.getContext(), "Can't add less than 0", Toast.LENGTH_SHORT).show();
} else {
counter[0] -= 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
}
});
holder.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.decrement.setEnabled(true);
counter[0] += 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
If anyone knows this problem please inform me.
Thanks in advance
Well, I'm seeing some bad practices in your code:
Adapters hosted in main activity must be not static, what do you think if try accessing via recyclerView.getAdapter()
Please remove the next one in your adapter
final MainActivity mainActivity = new MainActivity();
So the problem that you are having is inside your click listener.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
if (s.isEmpty()) {
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
} else {
input.add(s); // <-------------- HERE
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
You add the new item to the array, however, the adapter never knows that there is a new item has been added.
Access to the instanced adapter which has been attached to RecyclerView in onCreate() step and update their data.

Set values ​back to start

If I click the button CHECKOUT a pop up shows up. In this pop up, you have the chance to abort the transaction. So if you abort the transaction all the values for the Items (French fires, Water, Burger) should be 0 again as seen in the picture below. Right now when i abort the transaction the values stay the way i configured them before. Can you help me with that?
OrderActivity.java
package com.nfc.netvision;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
import static android.widget.Toast.*;
public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {
RecyclerView recyclerView;
ArrayList<ModelOrder> orderArrayList;
TextView textView_order_price;
TextView textView_order_count;
Dialog epicDialog;
Button btnCheckout;
Button btnAbort;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
recyclerView = findViewById(R.id.recyclerview_order_scroll);
textView_order_price = findViewById(R.id.textView_order_price);
textView_order_count = findViewById(R.id.textView_order_count);
btnCheckout = (Button) findViewById(R.id.btnCheckout);
orderArrayList = new ArrayList<>();
orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager recLiLayoutManager = layoutManager;
recyclerView.setLayoutManager(recLiLayoutManager);
OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);
recyclerView.setAdapter(adapter);
epicDialog = new Dialog(this);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showWaitingPopUp();
}
});
}
private void showWaitingPopUp() {
epicDialog.setContentView(R.layout.order_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
btnAbort = (Button) epicDialog.findViewById(R.id.btnAbort);
btnAbort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.show();
}
#Override
public void onTotalChanged(String result) {
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.GERMANY);
textView_order_price.setText( n.format(Integer.parseInt(result)));
}
#Override
public void onCountChanged(String result) {
textView_order_count.setText(result);
}
}
OrderAdapter.java
package com.nfc.netvision;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.w3c.dom.Text;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
private int totalAmount;
private int totalItems;
private Context mContext;
private ArrayList<ModelOrder> nList;
private TotalListener listener;
interface TotalListener{
void onTotalChanged(String result);
void onCountChanged(String result);
}
OrderAdapter(Context context, ArrayList<ModelOrder> list, TotalListener listener) {
mContext = context;
nList = list;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final ModelOrder orderItem = nList.get(position);
ImageView image = holder.item_image;
final TextView name, place, price;
name = holder.item_name;
place = holder.item_place;
price = holder.item_price;
image.setImageResource(orderItem.getImage());
name.setText(orderItem.getName());
place.setText(orderItem.getPlace());
price.setText(orderItem.getPrice());
holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() > 0) {
orderItem.setCounter(orderItem.getCounter()-1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), false);
countItems(orderItem.getCounter(), false);
}
}
});
holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() < 9) {
orderItem.setCounter(orderItem.getCounter() + 1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), true);
countItems(orderItem.getCounter(), true);
}
}
});
}
#Override
public int getItemCount() {
return nList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView item_image;
TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.order_item_image);
item_name = itemView.findViewById(R.id.order_item_name);
item_place = itemView.findViewById(R.id.order_item_place);
item_price = itemView.findViewById(R.id.order_item_price);
order_item_minus = itemView.findViewById(R.id.order_item_minus);
order_item_plus = itemView.findViewById(R.id.order_item_plus);
order_item_count = itemView.findViewById(R.id.order_item_count);
}
}
private void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
listener.onTotalChanged(totalAmount+ "");
}
private void countItems(int pCounter, boolean pUpDown){
if (pUpDown){
totalItems = totalItems + 1;
}
else{
totalItems = totalItems - 1;
}
listener.onCountChanged(totalItems+ "");
}
}
They stay the way there were because inside your abort button's onClick you just dismiss the dialog and do not change the list values.
I suggest iterating through the list and setting all counters to 0.
Also, don't forget to notify your RecyclerView that you modified something, in this case you reset all counters to 0. Otherwise, you won't see the changes in your app.
private void showWaitingPopUp() {
epicDialog.setContentView(R.layout.order_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
btnAbort = epicDialog.findViewById(R.id.btnAbort);
btnAbort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set all orders count to 0
for (ModelOrder modelOrder: orderArrayList) {
modelOrder.setCounter(0);
}
// Notify RecyclerView about the changes
adapter.notifyDataSetChanged();
epicDialog.dismiss();
}
});
epicDialog.show();
}
I noticed you didn't have the adapter as a global variable so declare it as such:
public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {
// other variables
// Change adapter variable to global
OrderAdapter adapter;
// ...
Side notes: I also noticed that you passed your activity twice inside your OrderAdapter constructor.
OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);
You can simply just do:
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);
Then inside your constructor:
OrderAdapter(Context context, ArrayList<ModelOrder> list) {
mContext = context;
nList = list;
// You can simply cast the context to the listener
listener = (TotalListener) context;
}
Hope my answer helps, happy coding!
Edit: I moved my answers to OP's other questions in the chat.

How do I extablish context for an Activity within a recyclerview adapter

I have buttons within the rows of a recyclerview within a fragment within an activity. When the user clicks one of the buttons, I want to switch to a different activity. How do I establish context for the Intent to switch to the new activity.
OR, should I move the onClickListener back to the fragment or activity (is it incorrect to place onClickListener within the recyclerview adapter code). If so, how do I obtain reference to the button clicked from outside the recyclerview adapter.
Here is the fragment code (CheckInRecentList.java)
package com.example.checkingin;
import android.app.Application;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter mAdapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private Context context;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_check_in_recent_list, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
mAdapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
LinearLayoutManager.VERTICAL));
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
ItemTouchHelper.SimpleCallback callback = new
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mAdapter.deleteItem(position);
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item " + (direction == ItemTouchHelper.RIGHT ? "deleted" : "archived") + ".", Snackbar.LENGTH_LONG);
snackbar.setAction(android.R.string.cancel, new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapter.undoDelete();
}
});
snackbar.show();
}
#Override
public void onChildDraw (Canvas c, RecyclerView
recyclerView, RecyclerView.ViewHolder viewHolder,float dX, float dY,
int actionState, boolean isCurrentlyActive){
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_left_background))
.addSwipeLeftActionIcon(R.drawable.ic_archive_white_24dp)
.addSwipeRightBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_right_background))
.addSwipeRightActionIcon(R.drawable.ic_delete_white_24dp)
.addSwipeRightLabel(getString(R.string.action_delete))
.setSwipeRightLabelColor(Color.WHITE)
.addSwipeLeftLabel(getString(R.string.action_archive))
.setSwipeLeftLabelColor(Color.WHITE)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
CustomToast newtoast = new CustomToast(getContext(),"you clicked on this" );
newtoast.show();
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
mAdapter.setCheckInList(allCheckIn);
}
});
}
}
Here is the recyclerview adapter code
package com.example.checkingin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private CheckInTable mRecentlyDeletedItem;
private int mCheckInTablePrimaryKey;
private int mRecentlyDeletedItemPosition;
private Context context;
public CheckInListAdapter(int layoutId) {
Log.i(TAG, "CheckInListAdapter: ");
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
Log.i(TAG, "setCheckInList: ");
notifyDataSetChanged();
}
public void deleteItem(int position) {
mRecentlyDeletedItem = checkInList.get(position);
mRecentlyDeletedItemPosition = position;
checkInList.remove(position);
notifyItemRemoved(position);
}
public void undoDelete() {
checkInList.add(mRecentlyDeletedItemPosition,
mRecentlyDeletedItem);
notifyItemInserted(mRecentlyDeletedItemPosition);
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInTablePrimaryKey = holder.checkInTablePrimaryKey;
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
Log.i(TAG, "onBindViewHolder: ");
//checkInTablePrimaryKey.setText(checkInList.get(listPosition).getCheckInTablePrimaryKey());
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
Integer value = (checkInList.get(listPosition).getCheckInTablePrimaryKey());
Intent intent = new Intent(context, CheckInNew.class);
intent.putExtra("checkInTablePrimaryKey",value);
context.startActivity(intent);
//Bundle extras = getIntent().getExtras();
//if (extras != null) {
// String value = extras.getInt("checkInTablePrimaryKey");
//The key argument here must match that used in the other activity
//}
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInTablePrimaryKey;
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInTablePrimaryKey = itemView.findViewById(R.id.checkInTablePrimaryKey);
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
}
}
}
Here is the Activity code CheckIn.java
package com.example.checkingin;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.view.Menu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
public class CheckIn extends AppCompatActivity implements
CheckInRecentList.OnFragmentInteractionListener,
CheckInApproveRequested.OnFragmentInteractionListener,
CheckInSearch.OnFragmentInteractionListener {
//private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_in);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
//MobileAds.initialize(this, new OnInitializationCompleteListener() {
// #Override
// public void onInitializationComplete(InitializationStatus initializationStatus) {
// }
//});
//mAdView = findViewById(R.id.adView);
//AdRequest adRequest = new AdRequest.Builder().build();
//mAdView.loadAd(adRequest);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerUtil.getDrawer(this,toolbar);
configureTabLayout();
}
private void configureTabLayout() {
TabLayout tabLayout = findViewById(R.id.check_in_main_tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Recent"));
tabLayout.addTab(tabLayout.newTab().setText("Approve Requested"));
tabLayout.addTab(tabLayout.newTab().setText("Search"));
final ViewPager viewPager = findViewById(R.id.check_in_main_pager);
final PagerAdapter adapter = new CheckInMainPagerAdapter
(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check_in, menu);
return true;
}
}
In the constructor of CheckInListAdapter pass another argument as context
public CheckInListAdapter(int layoutId, Context context) {
Log.i(TAG, "CheckInListAdapter: ");
checkInListLayout = layoutId;
this.context = context
}

How to solve the auto-clicking of buttons in recyclerview? is that a bug?

For my android project, I have used the recycle view in a layout which has 10+ view-holders each has a button and a text.
Whenever I click the button in the first item or view-holder, the 8th item is also auto clicked. And when I click the button in the 2nd one, the 9th button gets clicked.
So I searched this issue on google, then I found that this problem is a rare one.
And I also got a solution for this type, but that solved my problem partially.
So I want to know whether it is a bug or my mistake??
CaptionedImagesAdapterMenu.java
package com.boredboy.atithikhana;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.facebook.share.Share;
import java.util.Objects;
class CaptionedImagesAdapterMenu extends
RecyclerView.Adapter<CaptionedImagesAdapterMenu.ViewHolder>{
private String[] captions;
private String[] foodName;
private String[] desc;
private String[] price;
private Context context;
private Listener listener;
private Remover remover;
private SparseBooleanArray hidebtns = new SparseBooleanArray();
private SparseBooleanArray setnums = new SparseBooleanArray();
public interface Remover{
void onRemove(int position);
}
public interface Listener{
void onClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private Button button;
private ElegantNumberButton numberButton;
public ViewHolder(CardView v) {
super(v);
cardView = v;
this.button = v.findViewById(R.id.addbt);
this.numberButton = v.findViewById(R.id.numberincdec);
}
}
public CaptionedImagesAdapterMenu(Context context,String[] foodName, String[] desc,String[] captions, String[] price){
this.context = context;
this.foodName = foodName;
this.captions = captions;
this.desc = desc;
this.price = price;
}
public void setListener(Listener listener){
this.listener = listener;
}
public void setRemover(Remover remover){
this.remover =remover;
}
#Override
public int getItemCount(){
return captions.length;
}
#Override
public CaptionedImagesAdapterMenu.ViewHolder onCreateViewHolder(
ViewGroup parent, int viewType){
CardView cv = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_captioned_image_menu, parent, false);;
return new ViewHolder(cv);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, #SuppressLint("RecyclerView") final int position){
SharedPreferences preferences = context.getSharedPreferences("NEWV",0);
SharedPreferences.Editor editor = preferences.edit();
SharedPreferences prr = context.getSharedPreferences("ELEV",0);
SharedPreferences.Editor editor1 = prr.edit();
holder.button.setVisibility(hidebtns.get(position,false)?View.GONE:View.VISIBLE);
holder.numberButton.setVisibility(hidebtns.get(position,false)?View.VISIBLE:View.GONE);
String elval = prr.getString("elev","1");
holder.numberButton.setNumber(Objects.requireNonNull(setnums.get(position) ? elval : "1"));
CardView cardView = holder.cardView;
TextView textView = cardView.findViewById(R.id.info_text);
textView.setText(captions[position]);
TextView textView1 = cardView.findViewById(R.id.info_menu);
textView1.setText(desc[position]);
TextView textView2 = cardView.findViewById(R.id.info_price);
textView2.setText("₹ " + price[position]);
TextView textView3 = cardView.findViewById(R.id.food_Info);
textView3.setText(foodName[position]);
holder.button.setOnClickListener(view -> {
holder.button.setVisibility(View.GONE);
holder.numberButton.setVisibility(View.VISIBLE);
holder.numberButton.setNumber("1");
hidebtns.put(position,true);
setnums.put(position,false);
editor.putString("newv", String.valueOf(holder.numberButton.getNumber()));
editor.apply();
if(listener!=null)
{
listener.onClick(position);
}
});
holder.numberButton.setOnValueChangeListener((view, oldValue, newValue) -> {
if (newValue < 1) {
holder.button.setVisibility(View.VISIBLE);
holder.numberButton.setVisibility(View.GONE);
editor1.clear();
editor1.putString("elev", String.valueOf(newValue));
editor1.apply();
hidebtns.put(position,false );
setnums.put(position,true);
if (remover != null)
{
remover.onRemove(position);
}
editor.clear();
editor.apply();
}
if (newValue > 0) {
editor.putString("newv", String.valueOf(newValue));
editor.apply();
editor1.clear();
editor1.putString("elev", String.valueOf(newValue));
editor1.apply();
hidebtns.put(position,true);
setnums.put(position,true);
if(listener!=null)
{
listener.onClick(position);
}
}
});
}
}
As you know recyclerview recycle view for better performance.
While watching your code there is some visibility changes in view of your viewholder.
Just give a try for this solution.
Under onBindViewHolder add condition which checks data in your preference with respective your String.valueOf(holder.numberButton.getNumber()) and toggle visibility of your holder.button holder.numberButton view.

How can i get the 3 textview from recyclerview and pass it to dialogbox

Im new to android programming so can you provide me the right code.
this is my code. the data is from sqlite. my problem is . How can i get the 3 textview from recyclerview and pass it to dialogbox when clicked? i finally made dialogbox but i can get only the position of the item i want to get all of the three textview data. please help me.
FragmentMeal.java
package inncharge.poy.madrigal.innchargev1.fragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.database.DatabaseHelper;
import inncharge.poy.madrigal.innchargev1.adapters.VivzAdapter;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentMeal#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentMeal extends Fragment {
private DatabaseHelper db;
private RecyclerView recyclerView;
private VivzAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentMeal.
*/
// TODO: Rename and change types and number of parameters
public static FragmentMeal newInstance(String param1, String param2) {
FragmentMeal fragment = new FragmentMeal();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentMeal() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
db = new DatabaseHelper(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meal, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.mealList);
adapter = new VivzAdapter(getActivity(),db.getMealData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int postion) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
final EditText editText = (EditText)dialog.findViewById(R.id.editText_pin);
Button submitButton = (Button)dialog.findViewById(R.id.submit_button);
Button cancelButton = (Button)dialog.findViewById(R.id.cancel_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText.getText().toString();
Toast.makeText(getActivity(), "Pin submitted is : " + text, Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "onLongClick" + position, Toast.LENGTH_SHORT).show();
}
}));
return view;
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
Log.d("VIVZ", "constructor invoked ");
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("VIVZ","onSingleTapUp " + e);
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null){
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
Log.d("VIVZ", "onLongPress " + e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("VIVZ","onTouchEvent "+ e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View arg1, int arg2);
public void onLongClick(View view, int position);
}
}
VivzAdapter.java
package inncharge.poy.madrigal.innchargev1.adapters;
import android.content.ClipData;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.fragments.FragmentMeal;
import inncharge.poy.madrigal.innchargev1.pojo.Contact;
import inncharge.poy.madrigal.innchargev1.pojo.Information;
/**
* Created by Madrigal on 7/18/2015.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder> {
private Context context;
private final LayoutInflater inflater;
List<Contact> data = Collections.emptyList();
public VivzAdapter(Context context, List<Contact> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
Log.d("VIVZ","onCreateHolder called ");
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
Log.d("VIVZ", "onBindViewHolder called " + position);
holder.itemId.setText(String.valueOf(current.getId()));
holder.title.setText(current.getName());
holder.email.setText(current.getEmail());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public TextView email;
public TextView itemId;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listTextName);
email = (TextView) itemView.findViewById(R.id.listTextUname);
itemId = (TextView) itemView.findViewById(R.id.listTextId);
}
#Override
public void onClick(View v) {
}
}
}
Slidenerd makes some great videos, he helped me a lot as well when I started.
You might want to reconsider what you're trying to do and approach it differently... Why would you want to pass 3 textview from your UI into a dialog?
This is going to be painful.
Seems like you're going to have to extend DialogFragment (i'm assuming that's what you're using for a dialog, maybe an alert?). Create a static factory method inside the DialogFragment like this...
public class MyDialog extends DialogFragment {
private static tv1, tv2, tv3;
public static MyDialog newInstance(TextView tv1, TextView tv2, TextView tv3){
MyDialog.tv1 = tv1;
MyDialog.tv2 = tv2;
MyDialog.tv3 = tv3;
return new MyDialog();
}
}
Once you have this complete, create this dialog fragment inside that onClick method in the ViewHolder class. Instantiate the DialogFragment by doing this...
MyDialog.newInstance(title,email,itemId).show(getFragmentManager(),"dialog_tag");
Like i said before, it's seems sloppy and is probably error prone. There may be a better way of doing this but this is all I can think of off the top of my head. Let me know how it works out for you.. or perhaps revise your question so we can better help you reach a better solution to what you're trying to do.

Categories

Resources