I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);
Related
My fragment has a Recycler View. Therefore I have a RecyclerView Adapter too. From this Adapter, I am opening an AlertDialog. When I click OK, I need to pass the onclick event from my DialogFragment back to my RecyclerView Adapter.
Currently, I am doing it like here, but this passes the event back to the activity and not to the RecyclerView Adapter.
public class FreshwaterRecyclerViewAdapter extends RecyclerView.Adapter<FreshwaterRecyclerViewAdapter.ViewHolder> implements BiotopeDialogFragment.NoticeDialogListener {
private List<Biotope> data;
private LayoutInflater layoutInflater;
FreshwaterRecyclerViewAdapter(Context context, List<Biotope> data) {
this.layoutInflater = LayoutInflater.from(context);
this.data = data;
}
//The dialog fragment receives a reference to this Activity through the
//Fragment.onAttach() callback, which it uses to call the following methods
//defined by the NoticeDialogFragment.NoticeDialogListener interface
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
notifyItemInserted(getItemCount()-1);
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == R.layout.biotope_cardview){
itemView = layoutInflater.inflate(R.layout.biotope_cardview, parent, false);
} else {
itemView = layoutInflater.inflate(R.layout.biotope_add_button, parent, false);
}
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (position == data.size()) {
holder.imageButtonAddBiotope.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = ((AppCompatActivity) layoutInflater.getContext()).getSupportFragmentManager();
DialogFragment dialog = new BiotopeDialogFragment();
dialog.show(fragmentManager, "NoticeDialogFragment");
}
});
} else {
holder.textViewBiotopeTitle.setText(getItem(position).name);
Picasso.get().load(Uri.parse(getItem(position).imageUri)).into(holder.imageViewBiotope);
LastValuesRecyclerViewAdapter recyclerAdapter = new LastValuesRecyclerViewAdapter(layoutInflater.getContext(), getData());
holder.recyclerViewLastValues.setLayoutManager(new LinearLayoutManager(layoutInflater.getContext(), LinearLayoutManager.HORIZONTAL, false));
holder.recyclerViewLastValues.setAdapter(recyclerAdapter);
}
}
//total number of rows
#Override
public int getItemCount() {
return data.size() + 1; //+1 for the add button
}
#Override
public int getItemViewType(int position) {
return (position == data.size()) ? R.layout.biotope_add_button : R.layout.biotope_cardview;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView textViewBiotopeTitle;
private ImageView imageViewBiotope;
private RecyclerView recyclerViewLastValues;
private ImageButton imageButtonAddBiotope;
public ViewHolder(View view) {
super(view);
textViewBiotopeTitle = (TextView) view.findViewById(R.id.textViewBiotopeTitle);
imageViewBiotope = (ImageView) view.findViewById(R.id.imageViewBiotopeCardview);
recyclerViewLastValues = (RecyclerView) view.findViewById(R.id.recyclerViewLastValues);
imageButtonAddBiotope = (ImageButton) view.findViewById(R.id.imageButtonAddBiotope);
}
}
Biotope getItem(int id) {
return data.get(id);
}
private List<String> getData() {
List<String> data = new ArrayList<>();
data.add("PO4");
data.add("NO3");
return data;
}
}
This is my dialog.
public class BiotopeDialogFragment extends DialogFragment {
private NoticeDialogListener listener;
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
//Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
//Verify that the host activity implements the callback interface
try {
//Instantiate the NoticeDialogListener so we can send events to the host
listener = (NoticeDialogListener) context;
} catch (ClassCastException e) {
//The activity doesn't implement the interface, throw exception
throw new ClassCastException("FreshwaterRecyclerViewAdapter must implement NoticeDialogListener | Context: " + context.toString());
}
}
public static final String TAG = "biotope_dialog_fragment";
private ActivityResultLauncher<Intent> activityResultLauncher;
private Uri imageUri = null;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getContext());
LayoutInflater inflater = requireActivity().getLayoutInflater();
//Inflate and set the layout for the dialog
//Pass null as the parent view because its going in the dialog layout
View view = inflater.inflate(R.layout.fragment_dialog_biotope, null, false);
builder.setView(view);
View colorPickerPreviewView = view.findViewById(R.id.colorPickerPreviewView);
ColorPickerView colorPickerView = view.findViewById(R.id.colorPickerView);
ImageView imageViewBiotope = view.findViewById(R.id.imageViewBiotopePreview);
TextInputEditText textFieldBiotopeName = view.findViewById(R.id.textFieldBiotopeName);
builder.setTitle("New biotope")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
BiotopeDatabase database = BiotopeDatabase.getDbInstance(requireContext().getApplicationContext());
Biotope biotope = new Biotope();
if (textFieldBiotopeName.getText() != null) {
biotope.name = textFieldBiotopeName.getText().toString();
} else {
biotope.name = "";
}
if (imageUri != null) {
biotope.imageUri = imageUri.toString();
} else {
biotope.imageUri = "";
}
biotope.color = colorPickerView.getColor();
database.biotopeDao().insertAll(biotope);
//Send the positive button event back to the host activity
listener.onDialogPositiveClick(BiotopeDialogFragment.this);
}
})
.setNegativeButton("noke", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Send the negative button event back to the host activity
listener.onDialogNegativeClick(BiotopeDialogFragment.this);
Objects.requireNonNull(BiotopeDialogFragment.this.getDialog()).cancel();
}
});
return builder.create();
}
public static BiotopeDialogFragment display(FragmentManager fragmentManager) {
BiotopeDialogFragment fragment = new BiotopeDialogFragment();
fragment.show(fragmentManager, TAG);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
This is my fragment building the RecyclerView. Alternatively, I can pass the event back to the fragment if it is not possible to pass it to the adapter.
public class BiotopesFragment extends Fragment {
private FreshwaterRecyclerViewAdapter recyclerAdapter;
public static BiotopesFragment newInstance(String param1, String param2) {
BiotopesFragment fragment = new BiotopesFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_biotopes, container, false);
RecyclerView recyclerViewFreshwater = (RecyclerView) root.findViewById(R.id.recyclerViewFreshwater);
recyclerAdapter = new FreshwaterRecyclerViewAdapter(getContext(), getData());
recyclerViewFreshwater.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
recyclerViewFreshwater.setAdapter(recyclerAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
recyclerViewFreshwater.addItemDecoration(dividerItemDecoration);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.START | ItemTouchHelper.END, 0) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
Collections.swap(getData(), fromPosition, toPosition);
recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
}
});
itemTouchHelper.attachToRecyclerView(recyclerViewFreshwater);
return root;
}
private List<Biotope> getData() {
BiotopeDatabase database = BiotopeDatabase.getDbInstance(requireContext().getApplicationContext());
BiotopeDao biotopeDao = database.biotopeDao();
return biotopeDao.getAll();
}
}
Ideal Way to do this to create all UI component in Fragment not in the adapter . Create an interface to handle events in the fragment and provide callback to the fragment from adapter. now your Fragment should create all the UI component .
Now coming to the
How to provide callback from dialog fragment to Fragment.
You can use setTargetFragment but its deprecated . Now you can use setFragmentResultListener instead of setTargetFragment(), its the safest way i think. Once you get the result back in fragment you can call any method of your adapter.
I am actually working on a group project and I want to develop a functionnality for our application. My goal is to have a list of several items with their images and when I click on an Item of that list I want to have a text pop in the midle of the screen related to that particular item. I'm afraid I might be using the wrong technical Tools to do so. I am actually using a csv file for the list details, an adapter and a viewHolder for the list. Since I have no idea on what is wrong and what to do I link a big part of my code so you can check how I did until now. I can also give you my xml files if you need to check them out, a really big thanks in advance to all the answers and time spent on my problem
I already managed to have my list of items with the title and the picture (text from csv file) of each list item but I'm stuck on how to show a specific text for each ViewHolder.
this is my Adapter
public class Adapter extends RecyclerView.Adapter<ViewHolder> {
List<Departement> list;
Activity activity;
public Adapter(List<Departement> list, Activity activity) {
this.list = list;
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int itemType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.departement,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Departement departement = list.get(position);
viewHolder.bind(departement, activity);
}
#Override
public int getItemCount() {
return list.size();
}
}
my ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView textViewView;
private ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
textViewView = (TextView) itemView.findViewById(R.id.text);
imageView = (ImageView) itemView.findViewById(R.id.image);
}
public void bind(Departement departement, Activity activity){
textViewView.setText(departement.getText());
String uri = departement.getImageUrl();
int imageResource = activity.getResources().getIdentifier(uri, null, activity.getPackageName());
Drawable res = activity.getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);
}
}
each item of the list is a Departement
public class Departement {
private String text;
private String imageUrl;
public Departement(String text, String imageUrl) {
this.text = text;
this.imageUrl = imageUrl;
}
public String getText() {
return text;
}
public String getImageUrl() {
return imageUrl;
}
public void setText(String text) {
this.text = text;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
and finally my fragment
public class FragmentEspecesProches extends Fragment {
public final static char SEPARATOR=',';
private RecyclerView recyclerView;
private List<Departement> departementsList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_especes_proches, container, false);
ajouterDepartements();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new GridLayoutManager(this,2));
recyclerView.setAdapter(new Adapter(departementsList, getActivity()));
return view;
}
private void ajouterDepartements() {
ArrayList<String> lines = new ArrayList<>();
ArrayList<String[]> data = new ArrayList<>();
String sep = new Character(SEPARATOR).toString();
lines = UtilitaireResultat.readFile(getActivity().getResources().openRawResource(R.raw.departement));
for(String line : lines){
String[] oneData = line.split(sep);
data.add(oneData);
}
for(int i=0 ; i<data.size() ; i++){
String[] tabStr = data.get(i);
departementsList.add( new Departement( tabStr[2]+" - "+tabStr[3] ,"#drawable/"+tabStr[5] ));
}
}
}
you can implement item click listener like this
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvName;
public TextView tvHometown;
private Context context;
public ViewHolder(Context context, View itemView) {
super(itemView);
this.tvName = (TextView) itemView.findViewById(R.id.tvName);
this.tvHometown = (TextView) itemView.findViewById(R.id.tvHometown);
// Store the context
this.context = context;
// Attach a click listener to the entire row view
itemView.setOnClickListener(this);
}
// Handles the row being being clicked
#Override
public void onClick(View view) {
int position = getAdapterPosition(); // gets item position
// if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it
User user = users.get(position);
// We can access the data within the views
Toast.makeText(context, tvName.getText(), Toast.LENGTH_SHORT).show();
// }
}
}
Use onBindViewHolder to handle any interaction on your list items
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Departement departement = list.get(position);
viewHolder.bind(departement, activity);
viewHolder.itemView.setOnClickListener(//your action//);
}
ItemView is the whole item; you can access your textviews or imageviews as you use it on your bind method,
You can use your bind method to apply listeners.
Handle on click of the item inside your ViewHolder constructor
like ,
public ViewHolder(View itemView) {
super(itemView);
textViewView = (TextView) itemView.findViewById(R.id.text);
imageView = (ImageView) itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=getAdapterPosition();
Toast.makeText(context, list.get(position).getText(), Toast.LENGTH_SHORT).show();
}
});
}
Create your onClickListner interface as
interface RecylerViewItemClickListner
{
void onItemClick(Department item)
}
set the listner in Adapter class
private final RecylerViewItemClickListner mOnClickListener;
public Adapter(List<Departement> list, Activity activity) {
this.list = list;
this.activity = activity;
this.mOnClickListener = activity;
}
Now in ViewHolder class
public void bind(final Departement item, final mOnClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
mOnClickListener.onItemClick(item);
}
});
}
and change onBindViewHolder as below
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(items.get(position), mOnClickListener);
}
Override onItemClick(Department item) in activity
#override
onItemClick(Department item)
{
//show toast here...
}
implement OnClickListener in your ViewHolder class
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
#Override
public void onClick(View v)
{
//do action
}
}
Implement below method in your ViewHolder class.
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final User currentItem = users.get(getAdapterPosition());
Toast.makeText(mContext,currentItem.getText()+" is selected!",Toast.LENGTH_SHORT).show();
}
});
I Am working on project where users recognizes text(OCR) and then see all their text(OCR) history in another activity
App Link : https://play.google.com/store/apps/details?id=com.thetechroot.vision
I added shared preference and recycle view,
but i am only getting the first Text that was recognized
Working :-
Users Recognize Text(OCR) in Textactivity, then to view users history of scanned text(OCR) the history is shown in different activity
How Can I Saved Textview From One Activity to diff activity, and show it into recycleview using shared preference
TEXTACTIVTY.JAVA
textRecognizer.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(final FirebaseVisionText firebaseVisionText) {
translatelan(firebaseVisionText);
cd_text_re.setVisibility(View.VISIBLE);
spinnerlan.setVisibility(View.VISIBLE);
txtrecog.setText(firebaseVisionText.getText());
String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,firebaseVisionText.getText());
//int i = SharedCommon.getPreferencesInt(getApplicationContext(), key1,50);
final SharedCommon scth = new SharedCommon();
if (txtrecog.equals("")){
Toast.makeText(TextActivity.this, "Text: "+th, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(TextActivity.this, "Text: "+th, Toast.LENGTH_SHORT).show();
scth.putSharedPreferencesString(getApplicationContext(), SharedCommon.texthistory, th);
}
/* SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", String.valueOf(txtrecog.getText()));
editor.putInt("idName", 1);
editor.apply();*/
drawtextvision(firebaseVisionText);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> values;
ArrayList personNames;
Context context;
// 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 txtHeader;
public TextView txtFooter;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
}
public MyAdapter(Context context, ArrayList personNames) {
this.context = context;
this.personNames = personNames;
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(List<String> myDataset) {
values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
/*final String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,"");
*/
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.layout_history_text, 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(final 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.txtHeader.setText(name);
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
holder.txtFooter.setText("Footer: " + name);
}
});
//holder.txtFooter.setText("Footer: " + name);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
HISTORYACTIVITY.JAVA
public class AboutActivity extends AppCompatActivity {
/* WebView webView;*/
ProgressDialog mprogreeinternet;
String apppackagename = "com.thetechroot.vision";
int versionCode = BuildConfig.VERSION_CODE;
String versionName = BuildConfig.VERSION_NAME;
String appid = BuildConfig.APPLICATION_ID;
Button btnlimit;
WebView webview;
/* private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;*/
private RecyclerView recyclerView;
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
LinearLayout layouthide,layoutcredit;
int[] photos={R.drawable.logoam, R.drawable.iconshandwrit52,R.drawable.productsearch52,R.drawable.iconsqrcode52};
ImageButton arrdown,arrup,arrcre,arrcreup;
TextView txthistory;
TextView mItemDescription;
ImageButton mDescriptionImg,mupImg;
CardView cdhistory;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
/* btnlimit = (Button) findViewById(R.id.btnlimit);*/
final String th = SharedCommon.getSharedPreferencesString(getApplicationContext(), texthistory,"");
// Toast.makeText(this, ""+th, Toast.LENGTH_SHORT).show();
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
// recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
// Use the default animator
// recyclerView.setItemAnimator(new DefaultItemAnimator());
// you could add item decorators
// RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
// recyclerView.addItemDecoration(itemDecoration);
ArrayList<String> values = new ArrayList<String>();
/*for (int i = 0; i < 100; i++) {
values.add("Test" + i);
}*/
Toast.makeText(this, ""+String.valueOf(th), Toast.LENGTH_SHORT).show();
values.add(""+String.valueOf(th));
// specify an adapter (see also next example)
mAdapter = new MyAdapter(values);
recyclerView.setAdapter(mAdapter);
ItemTouchHelper.SimpleCallback simpleItemTouchCallback =
new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder
target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
// input.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startIntent = new Intent(AboutActivity.this, TextActivity.class);
startActivity(startIntent);
finish();
}
}
It's a position issue, you have to use setTag() and getTag(), check this
final String name = values.get(position);
**holder.txtFooter.setTag(name);**
holder.txtHeader.setText(name);
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
**holder.txtFooter.setText("Footer: " + v.getTag());**
}
});
Here TEXTACTIVTY.JAVA you are using single string, so instead of appending it to previous strings in shared preference you are replacing the history. Ideally you should save Strings array and retrieve the same. Currently values have size one because it has only one string.
First use Sting Array. To save String Array in shared preferences do the following
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
Then when you get the String from SharedPreferences simply parse it like this:
String[] playlists = playlist.split(",");
Refer Put and get String array from shared preferences
And https://blog.fossasia.org/storing-a-data-list-in-phimpme-android/ for more.
Problem: I want to go to the user's selected item
But I can not do it Selected position.
How can I get my position and stay in place???
I tried many ways but it was fruitless
Does my code have problems?
Any way to your opinion to help me
enter image description here
Code Adapter :
public class Adapter_Badan extends RecyclerView.Adapter<Adapter_Badan.ViewHolder> {
private Context context;
private List<Modell_Badan> modells;
public Adapter_Badan(Context context, List<Modell_Badan> modells) {
this.modells = modells;
this.context = context;
}
#NonNull
#Override
public Adapter_Badan.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new Adapter_Badan.ViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_badan, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final Adapter_Badan.ViewHolder holder, final int position) {
final Modell_Badan modell = modells.get(position);
holder.title.setText(modell.getTitle());
holder.content.setText(modell.getContent());
Picasso.get().load(modell.getImage()).into(holder.image1);
Picasso.get().load(modell.getImage2()).into(holder.image2);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent= new Intent(context,Badan.class);
intent.putExtra(Modell.ID,modell.getId());
intent.putExtra(Modell.TITLE,modell.getTitle());
intent.putExtra(Modell.CONTENT,modell.getContent());
intent.putExtra(Modell.IMAGE1,modell.getImage());
intent.putExtra(Modell.IMAGE12,modell.getImage2());
intent.putExtra("id", "1");
context.startActivity(intent);
((Activity)context).finish();
((Activity)context).overridePendingTransition(R.anim.alpha_f,R.anim.alpha_o);
}
}, 20);
}
});
}
#Override
public int getItemCount() {
return modells.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView image1;
private ImageView image2;
private TextView title;
private TextView content;
private RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
image1 = (ImageView) itemView.findViewById(R.id.image_badan);
image2 = (ImageView) itemView.findViewById(R.id.image2_badan);
title = (TextView) itemView.findViewById(R.id.title_badan);
content = (TextView) itemView.findViewById(R.id.content_badan);
}
}
But after the item is selected, the position is deleted
Can I prove the item's position?
Code Badan :
public class Badan extends AppCompatActivity {
private SharedP_Thems sharedP_thems;
private ImageView image_layout, image_layout2;
private TextView title_, content_;
private SharedPerfern sharedPerfern;
private Shared_Modell shared_modell;
private Adapter_Badan adapter_badan;
int a;
#Override
protected void onCreate(Bundle savedInstanceState) {
sharedPerfern = new SharedPerfern(this);
shared_modell = sharedPerfern.getShared();
sharedP_thems = new SharedP_Thems(this);
if (sharedP_thems.getLoad().equals(true))
setTheme(R.style.dark_them);
else setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_badan);
setUpToolbarLayout();
setUpView();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recy_badanw);
Adapter_Badan adapter_badan=new Adapter_Badan(this, Data_FackeGen.getModellBadan(this));
recyclerView.setLayoutManager( new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.HORIZONTAL));
recyclerView.setAdapter(adapter_badan);
getInten();
title_.setTextSize(shared_modell.getFonSize());
content_.setTextSize(shared_modell.getFonSize());
}
private void setUpToolbarLayout() {
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.tollbar_badab);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setUpView() {
image_layout = (ImageView) findViewById(R.id.image_badan2w);
image_layout2 = (ImageView) findViewById(R.id.image2_badanw);
title_ = (TextView) findViewById(R.id.title_badanw);
content_ = (TextView) findViewById(R.id.content_badanw);
}
private void getInten() {
Intent intent = getIntent();
int id = intent.getIntExtra(Modell.ID, 0);
String titel = intent.getStringExtra(Modell.TITLE);
String content = intent.getStringExtra(Modell.CONTENT);
int image1 = intent.getIntExtra(Modell.IMAGE1, 2);
int image2 = intent.getIntExtra(Modell.IMAGE12, 2);
Picasso.get().load(image1).into(image_layout);
Picasso.get().load(image2).into(image_layout2);
title_.setText(titel);
content_.setText(content);
}
}
Try moving the following code inside your click listener:
Modell_Badan modell = modells.get(position);
holder.title.setText(modell.getTitle());
holder.content.setText(modell.getContent());
Picasso.get().load(modell.getImage()).into(holder.image1);
Picasso.get().load(modell.getImage2()).into(holder.image2);
The problem was solved
I used the following method and responded
#Override
protected void onPause() {
super.onPause();
bundle = new Bundle();
Parcelable parcelable = recyclerView.getLayoutManager().onSaveInstanceState();
bundle.putParcelable(KEY_RECYCLER_STATE, parcelable);
}
#Override
protected void onResume()
{
super.onResume();
// restore RecyclerView state
if (bundle != null) {
Parcelable parcelable = bundle.getParcelable(KEY_RECYCLER_STATE);
recyclerView.getLayoutManager().onRestoreInstanceState(parcelable);
}
}
Android recyclerview item click event after update Recyclerview
Image description here
Mail 1 READ
Mail 2 Dont Read
In the item the click event I want to do this to me
How can you help make
public class Mesajlar_Adapter extends RecyclerView.Adapter<Mesajlar_Adapter.ViewHolder>{
private List<Mesajlar> resultModels;
private Context context;
public Mesajlar_Adapter(List<Mesajlar> resultModels, Context context) {
this.resultModels = resultModels;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mesajlar_listview_desing, parent, false);
ViewHolder view_holder = new ViewHolder(v);
return view_holder;
}
public void resetList() {
int size = this.resultModels.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
resultModels.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
public void addItem(Mesajlar item){
this.resultModels.add(item);
this.notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mesaj_id.setText(resultModels.get(position).getMESAJ_ID());
holder.kullanici_id.setText(resultModels.get(position).getKULLANICI());
holder.gelen_detay.setText(resultModels.get(position).getDETAY());
holder.kategori.setText(resultModels.get(position).getKATEGORI());
holder.konu.setText(resultModels.get(position).getKONU());
holder.tarih.setText(resultModels.get(position).getKAYIT_TARIHI());
String a = resultModels.get(position).getOKUNDU();
holder.okunma.setText(a);
if (a.equals("Hayir")){
holder.kategori.setTextColor(Color.BLACK);
holder.kategori.setTextSize(19);
holder.konu.setTextColor(Color.BLACK);
holder.konu.setTextSize(19);
holder.tarih.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return resultModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected TextView mesaj_id;
protected TextView kullanici_id;
protected TextView gelen_detay;
protected TextView konu;
protected TextView kategori;
protected TextView tarih;
protected CheckBox secim;
protected TextView okunma;
public ViewHolder(View view) {
super(view);
this.okunma =(TextView) view.findViewById(R.id.okunma);
this.mesaj_id = (TextView) view.findViewById(R.id.mesaj_id);
this.kullanici_id = (TextView) view.findViewById(R.id.kullanici_id);
this.gelen_detay = (TextView) view.findViewById(R.id.gelen_detay);
this.konu = (TextView) view.findViewById(R.id.Konu);
this.kategori = (TextView) view.findViewById(R.id.Kategori);
this.tarih = (TextView) view.findViewById(R.id.Tarih);
// this.secim = (CheckBox) view.findViewById(R.id.secim);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i=new Intent(context, Mesaj_Detay_Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String detay = gelen_detay.getText().toString();
String mesajid = mesaj_id.getText().toString();
String kullaniciid = kullanici_id.getText().toString();
i.putExtra("detay", detay);
i.putExtra("mesaj_id",mesajid);
i.putExtra("kullanici_id",kullaniciid);
context.startActivity(i);
}
}
}
First of all, add this interface for click event
public interface OnRecyclerItemViewClickListener {
void onClicked(int position, Mesajlar jar);
}
Model
public class Mesajlar {
...
boolean isClicked;
public boolean isClicked() {
return icClicked;
}
public void setClicked(boolean isClicked) {
this.isClicked = isClicked;
}
...
}
Adapter
private OnRecyclerItemViewClickListener listener;
public Mesajlar_Adapter(List<Mesajlar> resultModels, Context context, OnRecyclerItemViewClickListener listener) {
...
this.listener = listener;
}
...
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
if (resultModels.get(position).isClicked()) {
// change pressed background color here!
} else {
// change default background color here!
}
holder.itemView.setOnClickListener(v -> {
listener.onClicked(position, resultModels.get(position));
});
...
}
Activity
When you create RecyclerView Adapter, add OnRecyclerItemViewClickListener to constructor of adapter in Activity
Mesajlar_Adapter adapter = new Mesajlar_Adapter(list, context, new OnRecyclerItemViewClickListener {
#Override
public void onClicked(int position, Mesajlar jar) {
jar.setClicked(true);
adapter.notifyItemChanged(position);
Intent i = new Intent(YourActivity.this, Mesaj_Detay_Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("detay", jar.getDETAY());
i.putExtra("mesaj_id",jar.getMESAJ_ID());
i.putExtra("kullanici_id", jar.getKULLANICI());
startActivity(i);
}
});
Instead of handling click event in adapter level you can use interface and do it in activity level. Pass the adapter position to the activity, from activity you can do the actual process
see the sample http://wiki.workassis.com/android-recyclerview-example/