I'm using Viewpager for slider and initially Recyclerview... When I load image from Server to recycler it's done... Now what i want to do that when ever someone click on particular item, it should be opened in second activity in which ViewPager I use.. example: When I click first Image, it should open that image in viewPager(slider).... And Also when someone swipe on ViewPager's activity it should load more images....
Code is Below and don't know what to do next. Please Help me.
RecyclerView
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.myViewHolder> {
ArrayList<model> mdata;
Context context;
public RecyclerViewAdapter(){ }
public RecyclerViewAdapter(ArrayList<model> mdata, Context context) {
this.mdata = mdata;
this.context = context;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item,viewGroup,false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final myViewHolder holder, int i) {
Picasso.get().load(mdata.get(holder.getAdapterPosition()).getWallpaper()).into(holder.wallpaper);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("wallpaperUrl",mdata.get(holder.getAdapterPosition()).getWallpaper());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mdata.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
ImageView wallpaper;
Button set;
public myViewHolder(#NonNull View itemView) {
super(itemView);
wallpaper = itemView.findViewById(R.id.wallpaper);
set = itemView.findViewById(R.id.set);
}
}
Second Activity which have ViewPager:
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
btn = findViewById(R.id.setWallpaper);
mdata = new ArrayList<model>();
viewPager = findViewById(R.id.viewPager);
Intent intent = getIntent();
Integer[] colors_temp ={getResources().getColor(R.color.color1),
getResources().getColor(R.color.color2),
getResources().getColor(R.color.color3),
getResources().getColor(R.color.color4),
} ;
colors = colors_temp;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffSet, int pixels) {
if (position < adapter.getCount() -1 && position <(colors.length) -1){
viewPager.setBackgroundColor(
(Integer) argbEvaluator.evaluate
(positionOffSet,
colors[position],
colors[position + 1]));
}else{
viewPager.setBackgroundColor(colors[colors.length - 1]);
}
}
#Override
public void onPageSelected(final int i) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadImage downloadImage = new DownloadImage();
Bitmap bitmap = null;
try{
bitmap =
downloadImage.execute(mdata.get(i).getWallpaper()).get();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(SecondActivity.this, "Something went
Wrong! ", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
mDatabase = FirebaseDatabase.getInstance();
mReference = mDatabase.getReference().child("wallpapers");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
model data = dataSnapshot1.getValue(model.class);
mdata.add(data);
}
adapter = new Adapter(mdata,getApplicationContext());
viewPager.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SecondActivity.this, "Failed! "+databaseError,
Toast.LENGTH_SHORT).show();
}
});
}
MyAdapter:
public class Adapter extends PagerAdapter {
ArrayList<model> mdata;
Context context;
LayoutInflater inflater;
public Adapter(){
}
public Adapter(ArrayList<model> mdata, Context context) {
this.mdata = mdata;
this.context = context;
}
#Override
public int getCount() {
return mdata.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return view.equals(o);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.pager_item,container,false);
ImageView wallpaper;
Button btn;
wallpaper = view.findViewById(R.id.wallpaperImage);
Picasso.get().load(mdata.get(position).getWallpaper()).into(wallpaper);
container.addView(view,0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
If you are loading the images from the server, and each image has an id, pass the id into then intent. When you open up the view that needs the image that was clicked, make a service call to retrieve the image from the server using it's id.
In your enter code here, add setOnclickListener to holser.iytemView, then create an intent for navigating to the second activity, and add this code in onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: LoadingProfileActivity");
Intent intent = new Intent(getContext(), SecondActivity.class);
/*
Extras
*/
mainActivityContext.startActivity(intent);
}
});
If you want to send the image or id that contained in this row add intent.putExtra() after the intent is created.
Like if I want to display the image in second activity ill put in
Intent intent = new Intent(getContext(), SecondActivity.class);
intent.putExtra("image_url", imageResource);
In SecondActivity firsts get the imageresource from the intent
String imageResouce = getIntent.getStringExtra("image_url");
Then display the image in image view
Related
I am working on an app and i want it to scroll to a particular position i clicked from an adapter into another activity like the Instagram way of checking the smaller picture in the profile fragment and scrolling to the exact position in the other activity, that is from smaller picture to big picture.
MyAdapterCode
public class DisplayDuetAdapter extends RecyclerView.Adapter<DisplayDuetAdapter.ImageViewHolder> {
private Context mContext;
private List<DisplayDuet> mDisplayDuet;
public int position;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public DisplayDuetAdapter(Context context, List<DisplayDuet> displayDuet){
mContext = context;
mDisplayDuet = displayDuet;
}
#NonNull
#Override
public DisplayDuetAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.duet_display_item, viewGroup, false);
return new DisplayDuetAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final DisplayDuetAdapter.ImageViewHolder imageViewHolder, int i) {
final DisplayDuet displayDuet = mDisplayDuet.get(i);
// Glide.with(mContext).load(displayDuet.getOriginalpics()).into(imageViewHolder.original_pic);
Picasso.get().load(displayDuet.getOriginalpics()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.placeholder).into(imageViewHolder.original_pic, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(displayDuet.getOriginalpics()).placeholder(R.drawable.placeholder).into(imageViewHolder.original_pic);
}
});
// Glide.with(mContext).load(displayDuet.getPostimage()).into(imageViewHolder.post_pic);
Picasso.get().load(displayDuet.getPostimage()).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.placeholder).into(imageViewHolder.post_pic, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(displayDuet.getPostimage()).placeholder(R.drawable.placeholder).into(imageViewHolder.post_pic);
}
});
imageViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Intent intent = new Intent(mContext, DuetDisplayActivity.class);
intent.putExtra("postid", displayDuet.getPostid());
intent.putExtra("publisherid", displayDuet.getPublisher());
intent.putExtra("postduetid", displayDuet.getPostduetid());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mDisplayDuet.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView post_pic, original_pic;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
post_pic = itemView.findViewById(R.id.duet_pic_one);
original_pic = itemView.findViewById(R.id.duet_pic_two);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view, getAdapterPosition());
}
}
}
And the other activity code:
public class DuetDisplayActivity extends AppCompatActivity {
private String postid, publisher, postduetid;
private ImageView duet_close;
int position = 2;
private RecyclerView duet_show_recyclerView;
private DuetShowAdapter postAdapter;
private List<DisplayDuet> postList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duet_display);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisher = intent.getStringExtra("publisherid");
postduetid = intent.getStringExtra("postduetid");
duet_close = findViewById(R.id.close);
duet_show_recyclerView = findViewById(R.id.duet_show_recyclerView);
duet_show_recyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
duet_show_recyclerView.setLayoutManager(mLayoutManager);
postList = new ArrayList<>();
postAdapter = new DuetShowAdapter(this, postList);
duet_show_recyclerView.findViewHolderForAdapterPosition(position);
duet_show_recyclerView.setAdapter(postAdapter);
SnapHelper startSnapHelper = new PagerSnapHelper();
duet_show_recyclerView.setOnFlingListener(null);
startSnapHelper.attachToRecyclerView(duet_show_recyclerView);
duet_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
readPost();
}
private void readPost(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("DuetPics").child(postid);
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postList.clear();
for (DataSnapshot getsnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : getsnapshot.getChildren()) {
DisplayDuet displayDuet = snapshot.getValue(DisplayDuet.class);
postList.add(displayDuet);
}
Collections.reverse(postList);
postAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
What I understand from your question is that you want to pass the clicked position from your DisplayDuetAdapter to your DuetDisplayActivity.
If that is the case then you can pass it by the intent.
so pass the pressed item position in the DisplayDuetAdapter like this:
imageViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Intent intent = new Intent(mContext, DuetDisplayActivity.class);
//pass position like this
intent.putExtra("position", i);
intent.putExtra("postid", displayDuet.getPostid());
intent.putExtra("publisherid", displayDuet.getPublisher());
intent.putExtra("postduetid", displayDuet.getPostduetid());
mContext.startActivity(intent);
}
});
And get the position in the DuetDisplayActivity like this:
private int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duet_display);
Intent intent = getIntent();
postid = intent.getStringExtra("postid");
publisher = intent.getStringExtra("publisherid");
postduetid = intent.getStringExtra("postduetid");
//get the passed position
position = intent.getIntExtra("position");
............
............
update:
do this:
//get the passed position
position = intent.getIntExtra("position",0);
I want to start new activity and also passing JSON data to the new activity when i click an item on the recyclerview. i followed a video in youtube: https://www.youtube.com/watch?v=OfsiccfUWVc&index=6&list=PLaoF-xhnnrRW_FGeacuT1VLqnRMKfpp4v but the video didn't show how to go to new activity once i clicked the item on recyclerview. from the video, i wanted to click on the item and then new activity will bring me to the 'more detail page' about the item.
i have tried to do the intent but i am not sure how to call from the new main activity
this is my adapter code:
public class LonghouseAdapter extends RecyclerView.Adapter<LonghouseViewHolder> {
Context context;
List<LonghousesCategoryOne> longhousesCategoryOneList;
List<Category> categories;
private OnItemClickListener mlistener;
public LonghouseAdapter(Context context, List<LonghousesCategoryOne> longhousesCategoryOneList) {
this.context = context;
this.longhousesCategoryOneList = longhousesCategoryOneList;
}
#NonNull
#Override
public LonghouseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.longhouse_item_layout,null);
return new LonghouseViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull LonghouseViewHolder holder, final int position) {
holder.txt_price.setText(new StringBuilder("").append(longhousesCategoryOneList.get(position).Price));
holder.txt_longhouse_name.setText(new StringBuilder("").append(longhousesCategoryOneList.get(position).Name));
Picasso.with(context)
.load(longhousesCategoryOneList.get(position).Link)
.into(holder.img_longhouse);
holder.setItemClickListener(new IItemClickListener() {
#Override
public void onClick(View v) {
Common.currentCategory = categories.get(position);
context.startActivity(new Intent(context, descriptionsActivity.class));
}
});
}
#Override
public int getItemCount() {
return longhousesCategoryOneList.size();
}
}
this is my viewholder code:
public class LonghouseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView img_longhouse;
TextView txt_longhouse_name, txt_price;
public void setItemClickListener(IItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
IItemClickListener itemClickListener;
public LonghouseViewHolder(View itemView) {
super(itemView);
img_longhouse = (ImageView) itemView.findViewById(R.id.image_longhouse);
txt_longhouse_name = (TextView) itemView.findViewById(R.id.txt_longhouse_name);
txt_price = (TextView) itemView.findViewById(R.id.txt_longhouse_price);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v);
}
}
in my descriptionActivity, how do i set the item to my xml view?so far i have done this.
public class descriptionsActivity extends AppCompatActivity {
retreatSecondApi mservice;
ImageView img_longhouse;
TextView txt_longhouse_description, txt_price;
Context context;
List<LonghousesCategoryOne> longhousesCategoryOneList;
CompositeDisposable compositeDisposable = new CompositeDisposable();
#Override
protected void onCreate(Bundle savedInstanceState) {
mservice = Common.getAPI();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_descriptions);
img_longhouse = (ImageView)findViewById(R.id.placeImageView);
txt_longhouse_description = (TextView)findViewById(R.id.placeDescTextView);
txt_price = (TextView)findViewById(R.id.txt_longhouse_price);
txt_longhouse_description.setText()
}
}
Can anyone guide me on this? Thank you
As #rgaraisayev recommends in your onClick() listener uncomment the call to startActivity() i.e.
holder.setItemClickListener(new IItemClickListener() {
#Override
public void onClick(View v) {
Common.currentCategory = categories.get(position);
context.startActivity(new Intent(context, descriptionsActivity.class));
}
});
solved it, so in my holder view:
holder.setItemClickListener(new IItemClickListener() {
#Override
public void onClick(View v) {
Common.longhousedesc = longhousesCategoryOneList.get(position);
context.startActivity(new Intent(context, descriptionsActivity.class));
}
});
and in my new activity, i bind the data to my xml view like this:
txt_longhouse_description.setText(Common.longhousedesc.descriptions);
Good afternoon!
I have a fragment containing a recyclerView which holds bookmarked elements. The element layout has a star icon to delete the chosen item from SQLite database. When the icon is clicked, i need to set its tint to white then the position of that item needs to be saved in a list declared in my fragment. I am wondering how to do that.
Since we use adapters to bind elements I couldn't reference the icon from fragment to change the tint. Note that, It shouldn't refresh the page. After user presses back, It will save changes in db
Fragment
public class BookMarksFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
private BookMarksAdapter listAdapter;
private List<BookmarksModel> bookmarks = new ArrayList<>();
private FragmentBookmarksBinding binding;
private DBHelper dbHelper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Functions.setLanguages(App.getCurrentActivity());
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_bookmarks, container, false);
binding.refresher.setColorSchemeResources(R.color.drawer_background);
binding.refresher.setOnRefreshListener(this);
binding.refresher
.post(new Runnable() {
#Override
public void run() {
binding.refresher.setRefreshing(true);
setRefreshingState(true);
}
}
);
listAdapter = new BookMarksAdapter(getActivity(), bookmarks, this);
binding.bookmarkList.setLayoutManager(new LinearLayoutManager(getActivity()));
binding.bookmarkList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
return binding.getRoot();
}
private void setRefreshingState(final boolean b) {
binding.refresher.post(new Runnable() {
#Override
public void run() {
binding.refresher.setRefreshing(b);
getNews();
}
});
}
private void getNews() {
dbHelper = new DBHelper(getActivity(), "kunuz", null, 1);
bookmarks.clear();
bookmarks.addAll(dbHelper.getBookmarks());
if(bookmarks.size()==0){
binding.bookmarkList.setVisibility(View.GONE);
binding.emptyView.setVisibility(View.VISIBLE);
}else{
binding.emptyView.setVisibility(View.GONE);
binding.bookmarkList.setVisibility(View.VISIBLE);
}
binding.refresher.setRefreshing(false);
listAdapter.notifyDataSetChanged();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Constants.BOOKMARK_REQUEST_CODE:
if (resultCode == Constants.BOOKMARK_RESULT_CODE) {
binding.refresher
.post(new Runnable() {
#Override
public void run() {
binding.refresher.setRefreshing(true);
setRefreshingState(true);
}
}
);
}
break;
}
}
#Override
public void onRefresh() {
getNews();
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.star){
dbHelper.deleteFavorites(v.getTag().toString());
onRefresh();
}else if(v.getId()==R.id.bookmark_card_view){
Intent intent = new Intent(App.getInstance(), NewsViewActivity.class);
intent.putExtra(Constants.NEWS_CODE, v.getTag().toString());
getActivity().startActivity(intent);
}
}
}
Adapter
public class BookMarksAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private List<BookmarksModel> data;
private LayoutInflater inflater;
private View.OnClickListener listener;
public BookMarksAdapter(Context context, List<BookmarksModel> data, View.OnClickListener listener) {
this.context = context;
this.data = data;
this.listener = listener;
this.inflater = LayoutInflater.from(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
BookmarksItemBinding binding
= DataBindingUtil.inflate(inflater, R.layout.bookmarks_item, parent, false);
return new BookmarksHolder(binding.getRoot());
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final BookmarksModel item = data.get(position);
((BookmarksHolder)holder).binding.setNewsItem(item);
((BookmarksHolder)holder).binding.categoryIcon.setImageResource(Utils.getCategoryColorByName(item.getCategory()));
if (item.getImage_url() != null && !item.getImage_url().isEmpty()) { // TODO get image from cache
ImageLoader.getInstance()
.displayImage(item.getImage_url(), ((BookmarksHolder)holder).binding.newsImageView);
} else {
((BookmarksHolder)holder).binding.
newsImageView.setImageResource(R.drawable.kun_uz_logo_no_image);
}
((BookmarksHolder)holder).binding.star.setTag(item.getCode());
((BookmarksHolder)holder).binding.star.setOnClickListener(listener);
((BookmarksHolder)holder).binding.bookmarkCardView.setTag(item.getCode());
((BookmarksHolder)holder).binding.bookmarkCardView.setOnClickListener(listener);
}
#Override
public int getItemCount() {
return data.size();
}
public class BookmarksHolder extends RecyclerView.ViewHolder {
BookmarksItemBinding binding;
BookmarksHolder(View root) {
super(root);
binding = DataBindingUtil.bind(root);
}
}
}
OnClick listener on star icon sends clicked adapterPosition back to Fragment.
Fragment stores the change in database, updates list in the adapter.
Fragment calls adapters notifyItemChanged(position).
Adapters onBindViewHolder re-reads item on this position and sets star color appropriately.
You need to have some flag in BookmarksModel class to know whether the bookmarks is active(in db)/inactive(not in db) as in your case.
public BookmarksModel{
....
....
public isSaved;
}
Now in you onBindViewHolder method.
final BookmarksModel item = data.get(position);
((BookmarksHolder)holder).binding.setNewsItem(item);
.....
.....
if(item.isSaved){
((BookmarksHolder)holder).star.setAlpha(1f); //set your tint value
}else{
((BookmarksHolder)holder).star.setAlpha(0.5ff); //set your tint value
}
((BookmarksHolder)holder).binding.star.setTag(position); // just set the position
((BookmarksHolder)holder).binding.star.setOnClickListener(listener);
((BookmarksHolder)holder).binding.bookmarkCardView.setTag(position);
((BookmarksHolder)holder).binding.bookmarkCardView.setOnClickListener(listener);
In your fragment onClick()
public void onClick(View v) {
if (v.getId()==R.id.star){
int pos = (Integer)v.getTag();
BookmarksModel model = listAdapter.getList(pos); //create a getter in your
if(!model.isSaved) //toggled to saved bookmark
///////////////// your code to save bookmark
else
dbHelper.deleteFavorites(v.getTag().toString()); ///// your code for deleting bookmark
model.isSaved = !model.isSaved;
listAdapter.notifyItemChanged(pos); // refreshes your recyclerView item
}
}
Hope this helps.
I have a RecyclerView and each CardView contains a TextView and an ImageView. Whenever I click an item, I want to set the image visibility to VISIBLE and to set the previous clicked item image's visibility to INVISIBLE.
This is my Adapter class :
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{
private Context context;
private List<Category> lista;
private LayoutInflater layoutInflater;
private IncomeCategoryActivity activity;
private static final int CATEGORY_REQUEST=6;
private static final int ITEM_EDIT=1;
private static final int ITEM_DELETE=2;
private static final int EDIT_REQUEST=7;
private int current_pos=-1;
public CategoryAdapter(List<Category> lista, Context context, IncomeCategoryActivity activity) {
this.context = context;
this.lista = lista;
this.activity=activity;
layoutInflater=LayoutInflater.from(context);
}
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=layoutInflater.inflate(R.layout.category_layout, parent, false);
ViewHolder viewHolder=new ViewHolder(view, activity);
return viewHolder;
}
#Override
public void onBindViewHolder(CategoryAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(lista.get(position).getUri());
holder.textView.setText(lista.get(position).getCategory());
holder.position = position;
holder.category=lista.get(position);
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return lista.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public ImageView imageView;
public TextView textView;
public ImageView imageViewCheck;
public int position;
public Category category;
public IncomeCategoryActivity activity;
public ViewHolder(View itemView, IncomeCategoryActivity activity) {
super(itemView);
this.activity=activity;
imageView=itemView.findViewById(R.id.customCategoryImageView);
textView=itemView.findViewById(R.id.customCategoryTextView);
imageViewCheck=itemView.findViewById(R.id.customCheckImageView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
String aux=textView.getText().toString();
if(aux=="CATEGORIE NOUĂ"){
Intent intent=new Intent(context, CustomIncomeActivity.class);
activity.startActivityForResult(intent, CATEGORY_REQUEST);
}
else{
imageViewCheck.setVisibility(View.VISIBLE);
int pozitie_check=getLayoutPosition();
Intent intent=new Intent(context, AddIncomeActivity.class);
intent.putExtra("categorie_venit", aux);
intent.putExtra("position_check", pozitie_check);
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Selectează acțiunea");
MenuItem edit=menu.add(0, ITEM_EDIT, 0, "Modifică");
MenuItem delete=menu.add(0, ITEM_DELETE, 0, "Șterge");
edit.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
int position=getLayoutPosition();
if (item.getGroupId() == 0) {
if(item.getItemId()==ITEM_EDIT){
Category category=lista.get(position);
Intent intent=new Intent(activity, CustomIncomeActivity.class);
intent.putExtra("edit_icon", category.getUri());
intent.putExtra("edit_category", category.getCategory());
intent.putExtra("list_position", position);
activity.startActivityForResult(intent, EDIT_REQUEST);
}
else if(item.getItemId()==ITEM_DELETE){
lista.remove(position);
notifyDataSetChanged();
}
}
return true;
}
At this moment, whenever I click an item, there are two images VISIBLE on the RecyclerView: the clicked item's image and the previous clicked item's image. I think I need to get the previous View by its position and to manually set the visibility to INVISIBLE.
recycleView.getChildCount() and recycleView_parent.getChildAt() only gives the Adapter items which is shows only screen .
that means if your list has 200 items and the only 5 items shows on screen so we can find only 5 item with the help of recycleView
i am using one simple trick to solve the issue.
You can define Hashmap which hold your holder objects
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
ArrayList<Model> dataList;
Context context;
HashMap<Integer,ViewHolder> holderlist;
public MyAdapter(ArrayList<Model> dataList, Context context) {
this.context = context;
this.dataList = dataList;
holderlist = new HashMap<>();
}
And after that to save the holder in Hashmap
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(!holderlist.containsKey(position)){
holderlist.put(position,holder);
}
Create a method in Adapter.
public MyListAdapter.ViewHolder getViewByPosition(int position) {
return holderlist.get(position);
}
Call this method from your Activity or whenever you want.
for (int i = 0; i < datalList.size(); i++) {
MyAdapter.ViewHolder holder = ((MyAdapter)recycleView.getAdapter()).getViewByPosition(i);
View view = holder.itemView;
TextView tv = view.findViewById(R.id.tv);
}
I have created the demo you can refer it and implement for single selection
recyclerView.setAdapter(new RecyclerView.Adapter() {
int selected_position = -1;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerView.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
R.layout.row_color_list,parent,false)) {
#Override
public String toString() {
return super.toString();
}
};
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.image);
if(selected_position == position){
imageView.setVisibility(View.VISIBLE);
}else {
imageView.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected_position != holder.getAdapterPosition()){
selected_position = holder.getAdapterPosition();
notifyDataSetChanged();
}
}
});
}
#Override
public int getItemCount() {
return 20;
}
});
You can do as following:
1) Declare a global variable:
private int selectedPos = -100; // Put any irrelevant number you want
2) Set selected position onClick() :
#Override
public void onClick(View v) {
selectedPos = getAdapterPosition();
}
3) Check selected postion and assign visibility inside onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
if(position == selectedPos){
holder.imageViewCheck.setVisibility(View.VISIBLE);
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
Try this code..
add this code into adapter class for handling click event..
OnItemClick onItemClick;
public void setOnItemClick(OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
public interface OnItemClick {
void getPosition(String data); //pass any data to shared it.
}
after bind method..
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
// below code handle click event on recycler view item.
final String str=mStringList.get(position); // here your boject
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.getPosition(str); // pass your data.
}
});
}
after bind adapter into recycler view it means adapter not null then called below code..
adpater.setOnItemClick(new RecyclerViewAdpater.OnItemClick() {
#Override
public void getPosition(String data) {
// hear update your value for check into if condition.
data="sdfsdf";
adpater.notifyDataSetChanged();
}
});
and also read comments and also try to make custon class and access that object value and update after click it..
this code only how to handle click event into recycler view.
I am trying to pass view Id from Recyclerview Adapter to Activity,when the Recycler view List item is clicked.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> implements FastScrollRecyclerView.SectionedAdapter{
public interface OnRecyclerItemClickListener {
void onRecyclerItemClick(User data,int id);
}
List<User> dataSource;
private OnRecyclerItemClickListener onRecyclerItemClickListener;
private Context context;
public ActiveBeepsAdapter(List<User> dataArgs, OnRecyclerItemClickListener onRecyclerItemClickListener,Context context) {
this.dataSource = dataArgs;
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_active_message, parent, false);
ViewHolder viewHolder = new ViewHolder(view, onRecyclerItemClickListener);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
User user = dataSource.get(position);
holder.tvId.setText(user.getId());
Picasso.with(context)
.load(user.getProfilePicUrl())
.placeholder(R.drawable.bg_logo)
.error(R.drawable.bg_logo)
.transform(new CircleTransform())
.into(holder.ivUserProfile);
}
#Override
public int getItemCount() {
return dataSource.size();
}
#NonNull
#Override
public String getSectionName(int i) {
return String.valueOf(dataSource.get(i).getId().charAt(0));
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private OnRecyclerItemClickListener onRecyclerItemClickListener;
User data = new User();
TextView tvId;
ImageView ivUserProfile;
public ViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
super(itemView);
this.onRecyclerItemClickListener = onRecyclerItemClickListener;
tvId = (TextView)itemView.findViewById(R.id.tvName);
ivUserProfile = (ImageView)itemView.findViewById(R.id.ivProfilePic);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,id);
}
}
}
Suppose, If the Profile Image is clicked, the view id should sent to activity..
And My Activity
#EActivity
public class ActiveMessage extends AppCompatActivity implements Adapter.OnRecyclerItemClickListener{
#ViewById(R.id.toolbar)
Toolbar toolbar;
#ViewById(R.id.rvactiveMessage)
FastScrollRecyclerView rvmessage;
List<User> allUser;
#ViewById(R.id.toolbar_title)
TextView tv_toolbar;
#AfterViews
protected void init(){
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_drop_down_black_24dp));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tv_toolbar.setText("Active Message");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
allUser = new ArrayList<>();
User user;
String fullName[] = {"ajay","kamal","akhil"};
String id[] = {"its_ajay","its_kamal","its_akhil"};
for(int i=0;i<id.length;i++){
user = new User();
user.setId(id[i]);
user.setFullName(fullName[i]);
allUser.add(user);
}
Adapter adapter = new Adapter(allUser,this,getApplicationContext());
rvmessage.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvmessage.setAdapter(activeBeepsAdapter);
}
#Override
public void onRecyclerItemClick(User data,int id) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (id == R.id.tvName){
Log.d("Id",data.getId());
}
}
public void noInternet(){
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.alert_dialog);
dialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_active_message);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
In my Activity, If the ProfileImage is clicked, pop up the dialog box.
Also, i need to check if there is Internet Connection when the list Item is clicked.
In adapter onClick method instead of id pass view:
#Override
public void onClick(View v) {
int position = getAdapterPosition();
User user = dataSource.get(position);
int id = v.getId();
onRecyclerItemClickListener.onRecyclerItemClick(user,v);
}
Now in Activity
#Override
public void onRecyclerItemClick(User data,View view) {
if (!Utils.isNetworkAvailable(getApplicationContext())) {
noInternet();
}
// tvName has multiple Implementation
if (view.getId() == R.id.tvName){
Log.d("Id",data.getId());
}
}