I am trying to get position of the clicked item in RecyclerView. In adapter class, I am trying to create intent and send clicked item's contents. Also I created popup menu for two option. It is in adapter class too. onBindViewHolder position is works for puting contents in the rows of RecyclerView. However I couldn't reach that position from outside of method.
This is adapter class.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements PopupMenu.OnMenuItemClickListener {
public ArrayList<MovieModel.Results> resultList;
public Context context;
public RecyclerViewAdapter(ArrayList<MovieModel.Results> list, Context context) {
this.resultList = list;
this.context = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView posterImage;
ImageView addIcon;
TextView movieName;
TextView date;
TextView overview;
public ViewHolder(#NonNull View itemView) {
super(itemView);
posterImage = itemView.findViewById(R.id.movie_poster);
addIcon = itemView.findViewById(R.id.addImage);
movieName = itemView.findViewById(R.id.movieNameText);
date = itemView.findViewById(R.id.dateText);
overview = itemView.findViewById(R.id.overviewText);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_2, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (position < getItemCount()) {
String title = resultList.get(position).getTitle();
String date = resultList.get(position).getRelease_date();
String overview = resultList.get(position).getOverview();
String posterPath = resultList.get(position).getPoster_path();
holder.movieName.setText(title);
holder.date.setText(date);
holder.overview.setText(overview);
if (posterPath == null) {
holder.posterImage.setImageDrawable(context.getDrawable(R.drawable.no_poster));
} else {
Glide.with(context).load(FeedActivity.BASE_PHOTO_URL + posterPath).into(holder.posterImage);
}
int finalPosition = position;
holder.addIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "You clicked : " + finalPosition, Toast.LENGTH_SHORT).show();
showPopup(v);
}
});
}
position++;
}
private void showPopup(View v) {
PopupMenu popup = new PopupMenu(context,v);
popup.setOnMenuItemClickListener(this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu, popup.getMenu());
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
// Here I need to position of clicked item in Recyclerview, and I will get title, date etc.
int pos;
if(item.getItemId() == R.id.menuAdd){
// Find here to get position of clicked movie.
String title = resultList.get(pos).getTitle();
String date = resultList.get(pos).getRelease_date();
String overview = resultList.get(pos).getOverview();
String posterpath = resultList.get(pos).getPoster_path();
Intent intent1 = new Intent(context,ListActivity.class);
intent1.putExtra("title",title);
intent1.putExtra("date",date);
intent1.putExtra("overview",overview);
intent1.putExtra("posterpath",posterpath);
context.startActivity(intent1);
return true;
}
else if(item.getItemId() == R.id.menuShowDetails){
int movieId = resultList.get(pos).getMovieId();
Intent intent1 = new Intent(context, MovieDetails.class);
intent1.putExtra("movie_id",movieId);
context.startActivity(intent1);
return true;
}
return false;
}
#Override
public int getItemCount() {
return resultList.size();
}
}
You can use the ViewHolder's getAdapterPosition() to retrieve the item's position within an interface method. Then store the clicked position in a member variable.
Additionally, there shouldn't be a need to call position++ from within your onBindViewHolder.
// Create a member variable to store the clicked position
public int clickedPos = -1;
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// ...
holder.addIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// When you're inside the click listener interface,
// you can access the position using the ViewHolder.
// We'll store the position in the member variable in this case.
clickedPos = holder.getAdapterPosition();
}
});
// Remove the 'position++' call as the position should already be handled without explicitly updating it.
}
#Override
public boolean onMenuItemClick(MenuItem item) {
// You can use clickedPos here to perform whatever tasks you need.
// ...
}
Related
My RecyclerView Adapter is getting a bit busy. This is what I'm trying to do but with no success so far. When the user clicks on the popup menu, if the match isn't the currently active one they will be presented with 2 options (edit, delete). When the user selects edit, I'm making this the current match but I also want to move it to the top of the recyclerview. I have attempted this:
Collections.swap(mMatches, 0, position);
notifyItemMoved(position, 0);
but with no success. What can I do? The code is below:
public class MatchItemAdapter extends RecyclerView.Adapter<MatchItemAdapter.ViewHolder> {
private List<Match> mMatches;
private final Context mContext;
public MatchItemAdapter(Context context, List<Match> items) {
this.mContext = context;
this.mMatches = items;
}
#Override
public MatchItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater.inflate(R.layout.list_item_match, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final MatchItemAdapter.ViewHolder holder, final int position) {
final Match match = mMatches.get(position);
holder.matchIsActive = false;
final Match globalMatch = GlobalMatch.getMatch();
try {
holder.tvName.setText(match.getMatchName());
holder.tvDate.setText(match.getMatchDate());
holder.imageView.findViewById(R.id.imageView);
holder.hiddenMatchId.setText(match.getMatchId());
holder.container.findViewById(R.id.list_item_container);
Typeface bold = Typeface.create("san-serif", Typeface.BOLD);
String itemMatchId = holder.hiddenMatchId.getText().toString();
if (itemMatchId.equals(globalMatch.getMatchId())) {
holder.tvName.setTypeface(bold);
holder.container.setBackgroundColor(Color.parseColor("#a4a4a4"));
holder.tvName.setTextSize(24);
holder.matchIsActive = true;
}
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final PopupMenu popup = new PopupMenu(view.getContext(), holder.imageView);
if (!holder.matchIsActive) {
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_match:
GlobalMatch.changeMatch(match); // make this match the current match
// place a string representation of the current match in SharedPreferences
String jsonString = MatchHelper.jsonStringFromMatch(holder.imageView.getContext(), match);
SharedPreferences.Editor editor = holder.itemView.getContext().getSharedPreferences(
MY_GLOBAL_PREFS, holder.itemView.getContext().MODE_PRIVATE).edit();
editor.putString(CURRENT_MATCH, jsonString);
editor.apply();
// place this match at the top of the list
Collections.swap(mMatches, 0, position);
notifyItemMoved(position, 0);
Intent intent = new Intent(holder.itemView.getContext(), EditMatchActivity.class);
holder.itemView.getContext().startActivity(intent);
break;
case R.id.delete_match:
mMatches.remove(match);
notifyItemRemoved(position);
// delete file from internal storage
File dir = holder.itemView.getContext().getFilesDir();
File file = new File(dir, "match." + match.getMatchId() + ".json");
boolean deleted = file.delete();
Log.d("TAG", "The file was deleted");
break;
}
return false;
}
});
} else {
// If the current item is selected and you click on the side menu -> don't show delete
// delete isn't an option for active Matches
popup.getMenuInflater().inflate(R.menu.popup_menu_no_delete, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_match:
Intent intent = new Intent(holder.itemView.getContext(), EditMatchActivity.class);
holder.itemView.getContext().startActivity(intent);
break;
}
return false;
}
});
}
//displaying the popup menus
popup.show();
}
});
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.matchIsActive = true; // maybe this is redundant
String jsonString = MatchHelper.jsonStringFromMatch(holder.imageView.getContext(), match);
GlobalMatch.changeMatch(match);
SharedPreferences.Editor editor = holder.itemView.getContext().getSharedPreferences(
MY_GLOBAL_PREFS, holder.itemView.getContext().MODE_PRIVATE).edit();
editor.putString(CURRENT_MATCH, jsonString);
editor.apply();
Intent intent = new Intent(holder.itemView.getContext(), MainActivity.class);
holder.itemView.getContext().startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return mMatches.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvDate;
public ImageView imageView;
public TextView hiddenMatchId;
public View container;
boolean matchIsActive = false;
public ViewHolder(final View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.match_name);
tvDate = (TextView) itemView.findViewById(R.id.match_date);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
hiddenMatchId = (TextView) itemView.findViewById(R.id.match_id_hidden);
container = (View) itemView.findViewById(R.id.list_item_container);
}
}
}
I replaced the code with this and it worked:
Collections.swap(mMatches,holder.getAdapterPosition() ,0 );
mRecyclerView.getAdapter().notifyItemMoved(holder.getAdapterPosition(), 0);
If It didn't work, try using notifyDataSetChanged() after swapping data as the last resort.
I am not sure what's wrong with the code that cause the RecyclerView not updated its items. But from you code as shown below
Collections.swap(mMatches, 0, position);
notifyItemMoved(position, 0);
I found that, by swap two items in collection, you should move two items, not just one.
That is, for example, the original list is [0, 1, 2, 3, 4], swap(list, 0, 3) will get [3, 1, 2, 0, 4]. Therefore you need:
notifyItemMoved(position, 0);
notifyItemMoved(1, position);
in my adapter items can be selectable for show popup such as copy, cut or etc, now how can i get selected part of text on recyclerView item and position? i read more document about found this solution but i dont know how can i do that
this is my adapter which i would like to get selected part of text and postion:
public class ShowBookContentsAdapter extends RecyclerView.Adapter<ShowBookContentsAdapter.ShowBookContentsViewHolder> {
private List<Contents> list;
private Context context;
...
private fontFace setFontFace = fontFace.SHABNAM;
public ShowBookContentsAdapter(List<Contents> items, Context mContext, IonChangeBottomViewVisibility mOnChangeBottomViewVisibility, IonSelectText mIonSelectText) {
list = items;
context = mContext;
ionChangeBottomViewvisibility = mOnChangeBottomViewVisibility;
ionSelectText = mIonSelectText;
}
#Override
public ShowBookContentsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
switch (viewType) {
case 0:
layout = R.layout.item_book_content_paragraph;
break;
}
view = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
holder = new ShowBookContentsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ShowBookContentsViewHolder holder, final int position) {
switch (list.get(position).getContentType()) {
case 0:
makeSelectable(holder.book_content_paragraph);
implementingParagraphView(holder, position);
break;
}
}
private void implementingParagraphView(final ShowBookContentsViewHolder mHolder, final int position) {
holder = mHolder;
String content = list.get(position).getContent();
mHolder.book_content_paragraph.removeAllViews();
try {
Reader reader = new StringReader(content);
KetabkhanView ketabkhan = new KetabkhanView(context);
KetabkhanTagProcessor ketabkhanTagProcessor = new KetabkhanTagProcessor();
ketabkhanTagProcessor.parse(reader, ketabkhan);
mHolder.book_content_paragraph.addView(ketabkhan);
} catch (Exception e) {
e.printStackTrace();
Log.e("E ", e.getMessage());
throw new RuntimeException(e);
}
makeSelectable(mHolder.book_content_paragraph);
if (setFontFace == fontFace.SHABNAM)
Utils.overrideFonts(context, mHolder.book_content_paragraph, PersianFontType.SHABNAM);
else if (setFontFace == fontFace.SAHEL)
Utils.overrideFonts(context, mHolder.book_content_paragraph, PersianFontType.SAHEL);
//for show and hide bottom view
mHolder.book_content_paragraph.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ionChangeBottomViewvisibility != null) {
ionChangeBottomViewvisibility.onChange();
}
}
});
}
...
private void makeSelectable(ViewGroup viewGroup) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
makeSelectable((ViewGroup) child);
} else if (child instanceof TextView) {
((TextView) child).setTextIsSelectable(true);
((TextView) child).setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize == 0 ? 14 : textSize);
}
}
}
#Override
public int getItemViewType(int position) {
return list.get(position).getContentType();
}
#Override
public int getItemCount() {
return list.size();
}
public int getItemPosition(int itemId) {
return itemPositions.get(itemId);
}
public void setData(List<Contents> mContents) {
list.clear();
list.addAll(mContents);
}
public class ShowBookContentsViewHolder extends RecyclerView.ViewHolder {
#Nullable
#BindView(R.id.book_content_paragraph)
LinearLayout book_content_paragraph;
...
public ShowBookContentsViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
i make selectable text on items by this method: makeSelectable()
I have implemented the same using custom ActionMode Callback. We can set the custom Action Mode callback to a particular textview of recycler view item by setting textView.customSelectionActionModeCallback in the onBindViewHolder of recyclerView Adapter. In the custom Callback we can use the current position and selected text.
onBindViewHolder will look like this.
public void onBindViewHolder(myViewHolder holder, int position) {
//code
holder.textview. setCustomSelectionActionModeCallback(new CustomSelectionCallback(holder.taskName, position, mContext));
}
In the custom Callback we can send anything along with the position of the item.
Custom Selection Callback can be implemented as follows.
public class CustomSelectionCallback implements ActionMode.Callback {
private TextView mTextView;
private int position;
private Context mContext;
public CustomSelectionCallback(TextView text, int pos, Context context) {
this.mTextView = text;
this.position = pos;
this.mContext = context;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int start = mTextView.getSelectionStart();
int end = mTextView.getSelectionEnd();
Spannable wordtoSpan = (Spannable) mTextView.getText();
wordtoSpan.setSpan(new BackgroundColorSpan(Color.TRANSPARENT), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//copy the text when Copy Action Mode is clicked
if (item.getItemId() == android.R.id.copy) {
copyText(start, end);
mode.finish();
return true;
} else if (item.getItemId() == android.R.id.shareText) {
shareText(start, end);
mode.finish();
return true;
} else if (item.getItemId() == android.R.id.selectAll) {
selectAllText();
return true;
}
return true;
}
/**
* implement select all functionality id ActionMOde Menu
*/
private void selectAllText() {
Selection.setSelection((Spannable) mTextView.getText(), 0, mTextView.length());
}
private void shareText(int start, int end) {
CharSequence selectedTxt = mTextView.getText().subSequence(start, end);
String shareBody = selectedTxt.toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
mContext.startActivity(Intent.createChooser(sharingIntent, "SHARE"));
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
/**
* copy the selected text with start and end param to clipboard
*
* #param start start point of selection of the text view
* #param end end point of selection of the text view
*/
private void copyText(int start, int end) {
ClipboardManager clipboardManager = (ClipboardManager) mContext.
getSystemService(Context.CLIPBOARD_SERVICE);
CharSequence selectedTxt = mTextView.getText().subSequence(start, end);
ClipData clipData = ClipData.newPlainText("selected text label", selectedTxt);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(mContext, selectedTxt.toString() + " position " + position, Toast.LENGTH_LONG).show();
}
}
I am working on android example, when i click on checkbox then it gets the textviews value of first item(Position) in listview every time. so but i want to get value of selected (position) checkbox textview value. how to solve it please help .i am a fresher.Thanks in advances.
Some Code In BaseAdapter class
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null)
{
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.inactivelistview);
// viewItem.txtDescription = (TextView)convertView.findViewById(R.id.adapter_text_description);
convertView.setTag(viewItem);
}
else
{
viewItem = (ViewItem) convertView.getTag();
}
viewItem.txtTitle.setText(valueList.get(position).username);
// viewItem.txtDescription.setText(valueList.get(position).cources_description);
return convertView;
}
Some Code in activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_in_active_list);
listCollege = (ListView)findViewById(R.id.listCollege);
proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
checkbox = (CheckBox)findViewById(R.id.checkbox_me);
button =(Button)findViewById(R.id.button1);
new GetHttpResponse(this).execute();
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkbox_me:
if (checked) {
username = (TextView)findViewById(R.id.inactivelistview);
Username =username.getText().toString();
System.out.println("print username_=== "+Username);
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Do you want activate "+Username+"?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), Username+" acivated", Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
} else
break;
}
I am getting textviews value of first item(Position) in listview every time.
Please help me how to solve.help me update my code
Thank you so much.......
Note that checkbox return array as user can tick multiple elements.
ArrayList<String> selectedStrings = new ArrayList<String>();
The answer describe it in details.
use gettag on onCheckboxClicked method so that you can identify which row number checkbox is click . then you can get the textview of that row use row number
If your CheckBox is in ListView then no need to create ClickListener in Activity. Follow below steps to get selected text from ListView.
First create a model/pojo class, this will help you to store reference of selected CheckBox and also values which is going to show in ListView.
public class MyModel {
private boolean isSelected;
private String name;
public MyModel(boolean isSelected, String name) {
this.isSelected = isSelected;
this.name = name;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
this.isSelected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create a interface which will work as a callback.
public interface ItemSelectListener {
void getSelectedItemText(String text);
}
Refactor your BaseAdapter as now it will accept list of our Model class and also callback listener.
public MyAdapter extends BaseAdapter {
private final List<MyModel> mDataItems;
private final ItemSelectListener mItemListener;
public MyAdapter(List<MyModel> dataItems, ItemSelectListener itemListener)
mDataItems = dataItems;
mItemListener = itemListener;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewItem viewItem = null;
if(convertView == null) {
viewItem = new ViewItem();
LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//LayoutInflater layoutInfiater = LayoutInflater.from(context);
convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);
viewItem.txtTitle = (TextView)convertView.findViewById(R.id.inactivelistview);
// Add checkbox in your view item and confirm id of checkbox
viewItem.checkBox = (CheckBox)convertView.findViewById(R.id. checkbox_me);
}
else {
viewItem = (ViewItem) convertView.getTag();
}
final MyModel data = mDataItems.get(position);
viewItem.txtTitle.setText(data.getName());
viewItem.checkBox.setChecked(data.isSelected());
viewItem.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton button, boolean checked)
{
data.setSelected(checked);
if(checked) {
// Make sure you override this in your Activity
mItemListener.getSelectedItemText(data.getName());
}
}
});
return convertView;
}
}
Create datasource for ListView in your Activity.
BaseAdapter adapter = new BaseAdapter(dataItems, itemListener);
I have it clicked and it gets up to it and shows the right getText() method but the setText method is not working...
userAdapter.setOnEntryClickListener(new UserAdapter.OnEntryClickListener() {
#Override
public void onEntryClick(View view, int position) {
DatabaseUser user = dbUsersList.get(position);
TextView clickedView = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
if(view == clickedView) {
if (clickedView.getText().equals("following")) {
Log.d(Constants.DEBUG, " THE CLICK VIEW IS " + clickedView.getText());
//APPLY Following
String txtFollow = "follow";
clickedView.setText(txtFollow);
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(3);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
} else {
clickedView.setText("following");
if (user.getIsChanged() == 0) {
user.setIsChanged(1);
} else {
user.setIsChanged(0);
}
user.setIsType(0);
db.updateFollow(user);
userAdapter.notifyDataSetChanged();
}
} else {
Toast.makeText(getApplicationContext(), user.getUsername() + " is selected!", Toast.LENGTH_SHORT).show();
takeToUserProfile(dbUsersList.get(position));
}
}
});
Here is the adapter class:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.MyViewHolder> {
private List<DatabaseUser> dbUsersList, followingList;
private DatabaseHelper db;
private Context context;
private Typeface typeFace, italicTypeface, boldTypeface;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView userAdapterUsername, userAdapterFollowBtn;
public ImageView userAdapterUserPicture;
public MyViewHolder(View view) {
super(view);
userAdapterUsername = (TextView) view.findViewById(R.id.userAdapterUsername);
userAdapterFollowBtn = (TextView) view.findViewById(R.id.userAdapterFollowBtn);
userAdapterUserPicture = (ImageView) view.findViewById(R.id.userAdapterUserPicture);
Log.d(Constants.DEBUG, "IN MY VIEW HOLDER");
view.setOnClickListener(this);
userAdapterFollowBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnEntryClickListener != null) {
Log.d(Constants.DEBUG, "IN On click");
mOnEntryClickListener.onEntryClick(v, getAdapterPosition());
}
}
}
private static OnEntryClickListener mOnEntryClickListener;
public interface OnEntryClickListener {
void onEntryClick(View view, int position);
}
public void setOnEntryClickListener(OnEntryClickListener onEntryClickListener) {
mOnEntryClickListener = onEntryClickListener;
}
public UserAdapter(Context mContext, List<DatabaseUser> usersList, List<DatabaseUser> passedFollowing, Typeface myTypeface, Typeface myTypefaceItalic, Typeface myTypefaceBold) {
context = mContext;
dbUsersList = usersList;
followingList = passedFollowing;
typeFace = myTypeface;
italicTypeface = myTypefaceItalic;
boldTypeface = myTypefaceBold;
Log.d(Constants.DEBUG, "IN MY User ADAPTER CONSTRUCTOR");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.follow_item, parent, false);
Log.d(Constants.DEBUG, "RETURN ITEM VIEW HOLDER");
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DatabaseUser user = dbUsersList.get(position);
holder.userAdapterUsername.setTypeface(boldTypeface);
holder.userAdapterUsername.setText(user.getUsername());
final int pos = getItemViewType(position);
//TODO Create pic link
if(containsId(dbUsersList.get(pos), followingList)) {
//Then show following
holder.userAdapterFollowBtn.setText("following");
} else {
//show follow
holder.userAdapterFollowBtn.setText("follow");
}
String userspic = dbUsersList.get(pos).getPicture();
if(userspic == null) {
//SET DEFAULT OR PUT DEFAULT IN XML AND DO NOTHING IT SHOULD SHOW DEFAULT PIC
} else {
//TODO setupUser Pic
String img1 = "http://www.hindustantimes.com/Images/popup/2015/6/kungfu2.jpg";
Picasso.with(context).load(img1).transform(new RoundedTransformation()).into(holder.userAdapterUserPicture);
}
}
#Override
public int getItemCount() {
return dbUsersList.size();
}
public static boolean containsId(DatabaseUser currentUser, List<DatabaseUser> list) {
for (DatabaseUser object : list) {
if (currentUser.getUserId().equals(object.getUserId())) {
return true;
}
}
return false;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
your dbUsersList is not updating. please check your user object in dbUsersList after notify data set change.
What ended up being the problem is that I had passed in the followingList, so I never re-called to grab the new following from the db on update. The update was happening I just had to re-grab the followingList from the db to have an updated list to check against like so in a new method that was passing the list back to the contains method.
db.grabFollowersList();
I have shown a list of contacts in CardView on RecyclerView and now i want to open a context menu when i call OnLongClick event on particular CardView.
Like edit, delete options.
In CardView layout i have added two layout, left side contact are showing and right side two buttons added history and status where different event handlers handle.
If I press long click on CardView a popup window open where i can edit and delete contact and from those options like - delete or edit click event will handle for particular contact.
ContactAdapter code:
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
ArrayList<Contact> contacts = new ArrayList<Contact>();
Context ctx;
public ContactAdapter(ArrayList<Contact> contacts,Context ctx) {
this.contacts = contacts;
this.ctx = ctx;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view,ctx,contacts);
return contactViewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact CON = contacts.get(position);
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
TextView person_name, person_email,btn_history,btn_task_update;
ArrayList<Contact> contacts = new ArrayList<Contact>();
Context ctx;
CardView card_view;
public ContactViewHolder(View view, Context ctx ,ArrayList<Contact> contacts) {
super(view);
this.contacts=contacts;
this.ctx = ctx;
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
card_view = (CardView) view.findViewById(R.id.card_view);
btn_history = (TextView) view.findViewById(R.id.btn_history);
btn_task_update= (TextView) view.findViewById(R.id.btn_task_update);
card_view.setOnClickListener(this);
card_view.setOnLongClickListener(this);
btn_history.setOnClickListener(this);
btn_task_update.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Contact contact = this.contacts.get(position);
if(v.getId()==R.id.card_view) {
Toast.makeText(this.ctx, "position Card View" + position, Toast.LENGTH_SHORT).show();
}
else if(v.getId()==R.id.btn_history)
{
Toast.makeText(this.ctx, "position History" + position, Toast.LENGTH_SHORT).show();
}
else if(v.getId()==R.id.btn_task_update)
{
Toast.makeText(this.ctx, "position Task Status" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this.ctx, task_detail.class);
intent.putExtra("name", contact.getName());
intent.putExtra("email", contact.getEmail());
this.ctx.startActivity(intent);
}
}
#Override
public boolean onLongClick(View v) {
int position = getAdapterPosition();
Contact contact = this.contacts.get(position);
Toast.makeText(this.ctx, "position " + position, Toast.LENGTH_SHORT).show();
return true;
}
}
}
#Override
public boolean onLongClick(View v) {
if( v.getId() == R.id.card_view ) {
int position = getAdapterPosition();
Contact contact = this.contacts.get(position);
showDialog( contact, new CustomActionListener() {
void onAction( int actionType ) {
switch( actionType ) {
case OPTION_EDIT :
//edit contact here
break;
case OPTION_DELETE :
//delete contact here
break;
default :
//On dialog dismiss - do nothing
break;
}
}
} );
/* show your popup dialog here, it would be good
if you have an interface defined for the kind of action that was performed in dialog, using that,
perform required action here. */
}
return true;
}
// Your custom interface
public interface CustomActionListener {
void onAction( int actionType );
}
Define a showDialog function with popup window with buttons to complete the above pseudo code.