How to dynamically add and remove pages in Android ViewPager2? - java

Here is what I was trying to do. addNewQRCard() is onclick event fired by a button to add new images to viewpager. I have to always set the adapter to new items. But why in my case onStart() doesn't do that job. Please give me the best practice that I should use to add and delete views dynamically from viewPager2.
public class AddPage extends AppCompatActivity {
private ViewPager2 viewPager2;
private ArrayList<ModelItem> items;
private AdapterSlider adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_qrcode);
viewPager2 = findViewById(R.id.viewPagerImageSlider);
items = new ArrayList<>();
items.add(new ModelItem(R.drawable.image1));
adapter = new AdapterSlider(items,viewPager2);
viewPager2.setAdapter(adapter);
viewPager2.setClipToPadding(false);
viewPager2.setClipChildren(false);
viewPager2.setOffscreenPageLimit(3);
viewPager2.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
compositePageTransformer.addTransformer(new MarginPageTransformer(40));
compositePageTransformer.addTransformer(new ViewPager2.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
float r = 1 - Math.abs(position);
page.setScaleY(0.85f + r * 0.15f);
}
});
viewPager2.setPageTransformer(compositePageTransformer);
}
#Override
protected void onStart() {
super.onStart();
adapter = new AdapterQRSlider(sliderItems,viewPager2);
viewPager2.setAdapter(adapter);
}
public void addNewQRCard(View view) { //this is the button which i used to add new childs
items.add(new ModelSlider(R.drawable.image2));
adapter = new AdapterSlider(items,viewPager2);
viewPager2.setAdapter(adapter);
}
}
Adapter class
public class AdapterSliderextends RecyclerView.Adapter<AdapterSlider.ViewHolder>{
private ArrayList<ModelSlider> items;
private ViewPager2 viewPager2;
public AdapterSlider(ArrayList<ModelSlider> items, ViewPager2 viewPager2) {
this.items= items;
this.viewPager2 = viewPager2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.slide_item_container,
parent,
false
)
);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setImage(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageSlide);
}
void setImage(ModelSlider items){
imageView.setImageResource(sliderItem.getImage());
}
}
}
Model Class
public class ModelSlider {
private int image;
public ModelSlider(int image){
this.image = image;
}
public int getImage() {
return image;
}
}

You can notify adapter when you adding new items just like the way you do it with RecyclerView. Something like this
public void addNewQRCard(View view) {
items.add(new ModelSlider(R.drawable.image2));
// instead of of resetting adapter to ViewPager,
// just notify its adapter of item inserted
adapter.notifyItemInserted(items.size - 1)
}

Related

Display the passing data between two fragments in recyclerView

I have data taken from an API, I have added a button that when pressed will move (title, image, and some data from FRAGMENT to other FRAGMENT), this data is taken from RECYCLERLVIEW and will be shown in RECYCLERVIEW. But when the button is pressed, nothing happens and the data is not transmitted.
The project link if you want to take a deeper look "Mox Project"
Here's the first adapter that I send data from
--- CNNAdapter ---
private List<Item> items = null;
#SuppressLint("NotifyDataSetChanged")
public void setCNNList(List<Item> items) {
this.items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new NewsViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_news,
parent,
false
)
);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Item News = items.get(position);
((NewsViewHolder) holder).setData(News);
((NewsViewHolder) holder).sendData(News);
}
#Override
public int getItemCount() {
if (items == null) return 0;
return items.size();
}
static class NewsViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView title;
private final TextView description;
private final TextView source;
private final TextView author;
private final Button sendDataButton;
private final Activity activity = new Activity();
NewsViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image_news);
title = itemView.findViewById(R.id.title_news);
description = itemView.findViewById(R.id.description_news);
source = itemView.findViewById(R.id.source_news);
author = itemView.findViewById(R.id.author_name_news);
sendDataButton = itemView.findViewById(R.id.button_save);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void setData(Item news) {
Glide.get(itemView.getContext()).clearMemory();
// load images in MainThread
activity.runOnUiThread(() -> {
Glide.with(itemView.getContext())
.load((Objects.requireNonNull(news.getEnclosure())).getLink())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.transition(DrawableTransitionOptions.withCrossFade())
.into(image);
Glide.get(itemView.getContext()).clearMemory();
});
title.setText(news.getTitle());
description.setText(Html.fromHtml(Objects.requireNonNull(news.getDescription()).replaceAll("(<(/)img>)|(<img.+?>)", ""), Html.FROM_HTML_MODE_COMPACT));
source.setText(R.string.cnn);
author.setText(R.string.author);
}
void sendData(Item news) {
sendDataButton.setOnClickListener(v -> {
Bundle bundle = new Bundle();
bundle.putString("title", news.getTitle());
bundle.putString("image", Objects.requireNonNull(news.getEnclosure()).getLink());
bundle.putString("source", "CNN");
bundle.putString("author", "CNN editor's");
bundle.putString("link", news.getLink());
FavouriteFragment favouriteFragment = new FavouriteFragment();
favouriteFragment.setArguments(bundle);
});
}
}
Here's the second adapter that I get the data and set it
--- FavoriteAdapter ---
public class FavoriteAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Item> items = new ArrayList<>();;
private Context context;
#SuppressLint("NotifyDataSetChanged")
public void setFavoriteList(ArrayList<Item> items, Context context) {
this.items = items;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new FavoriteViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_save,
parent,
false
)
);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
((FavoriteViewHolder) holder).setData();
}
#Override
public int getItemCount() {
if (items == null) return 0;
return items.size();
}
static class FavoriteViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView title;
private final TextView source;
private final TextView author;
private final Activity activity = new Activity();
FavoriteViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image_article_save);
title = itemView.findViewById(R.id.title_article_save);
source = itemView.findViewById(R.id.source_article_save);
author = itemView.findViewById(R.id.author_name_article_save);
}
#RequiresApi(api = Build.VERSION_CODES.N)
void setData() {
FavouriteFragment favouriteFragment = new FavouriteFragment();
Bundle bundle = favouriteFragment.getArguments();
String getTitle = bundle.getString("title");
String getImage = bundle.getString("image");
String getSource = bundle.getString("source");
String getAuthor = bundle.getString("author");
String getLink = bundle.getString("link");
Glide.get(itemView.getContext()).clearMemory();
// load images in MainThread
activity.runOnUiThread (() -> {
Glide.with(itemView.getContext())
.load((getImage))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.transition(DrawableTransitionOptions.withCrossFade())
.into(image);
Glide.get(itemView.getContext()).clearMemory();
});
title.setText(getTitle);
source.setText(getSource);
author.setText(getAuthor);
}
}
My fragment that I display the data using recyclerview
--- FavouriteFragment ---
public class FavouriteFragment extends Fragment {
private FragmentFavouriteBinding binding;
ArrayList<Item> arrayList = new ArrayList<>();;
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentFavouriteBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
requireActivity().setTitle("");
initializeViews();
return view;
}
private void initializeViews() {
FavoriteAdapter adapter = new FavoriteAdapter();
binding.recyclerViewFavorites.setLayoutManager(new LinearLayoutManager(requireContext()));
binding.recyclerViewFavorites.setHasFixedSize(true);
binding.recyclerViewFavorites.setAdapter(adapter);
adapter.setFavoriteList(arrayList,getContext());
}
The project link if you want to take a deeper look "Mox Project"
Thank you for your help.
Possible problems or issues that may cause the button not to show the passed data.
remember a view will only display when it gets data.
Here are some resources that might help:
Passing Data between Fragments on Android Using ViewModel
Managing UI-related data in activity lifecycles
https://heartbeat.fritz.ai/passing-data-between-fragments-on-android-using-viewmodel-d47fa6773f9c
How to pass values between Fragments
https://android-developers.googleblog.com/2011/02/android-30-fragments-api.html
The displaying of Fragments is managed by FragmentManager. You must pass an instance of FragmentManager to CNNAdapter as follows:
public class CNNAdapter extends RecyclerView.Adapter<CNNAdapter.NewsViewHolder> {
private final FragmentManager mFragmentManager;
public CNNAdapter(FragmentManager mFragmentManager) {
this.mFragmentManager = mFragmentManager;
}
public void addData(List<> items) {
list.addAll(items);
notifyDataSetChanged();
}
}
And then you display the fragment as follows:
FavouriteFragment favouriteFragment = new FavouriteFragment();
favouriteFragment.setArguments(bundle);
mFragmentManager.beginTransaction().replace(R.id.fragment_container,favouriteFragment).commit();
R.id.fragment_container is the view ID of the container in the layout xml of the activity that hosts the fragment. The container is usually a FrameLayout.
And then you instantiate CNNAdapter in the Fragment like this:
CNNAdapter cnnAdapter = new CNNAdapter(getFragmentManager());

I need to implementation click listener class on item in recycle view when using adapter and array list

I want when user click on item in recycle move on second activity. I have the following adapter:
public class AdapterWassafat extends RecyclerView.Adapter<AdapterWassafat.ViewHolder> {
private ArrayList<Item> itemsList;
private Context mContext;
public AdapterWassafat(ArrayList<Item> itemsList, Context mContext) {
this.itemsList = itemsList;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_wasafat,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item item = itemsList.get(position);
holder.text.setText(item.getText());
}
#Override
public int getItemCount() {
return itemsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
public ViewHolder(#NonNull View itemView) {
super(itemView);
text = itemView.findViewById(R.id.text_card_main);
}
}
}
and I have this class to add on item list:
public class Item {
private String text;
public Item(String text) {
this.text = text;
}
public Item() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
and this class has recycle:
private AdapterWassafat adapter;
private RecyclerView recyclerView ;
private ArrayList<Item> myList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wasafat);
recyclerView = findViewById(R.id.wasafat_recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getBaseContext()));
adapter = new AdapterWassafat(getMyitem(),getBaseContext());
recyclerView.setAdapter(adapter);
}
private ArrayList<Item> getMyitem() {
ArrayList<Item> list = new ArrayList<>();
Item tips = new Item();
tips.setText("وصفة التمر ");
list.add(tips);
tips = new Item();
tips.setText("وصفة اللبن ");
list.add(tips);
tips = new Item();
tips.setText("وصفة الشاي الاخضر ");
list.add(tips);
return list;}
What do I need to make a recycle view when user click on item move on another activity? Like, as user clicks on item وصفة الشاي, to swap or move on into this activity and so on. I tried a lot of ways to make it both select or click, but that didn't succeed.
In the Adapter:
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item item = itemsList.get(position);
Context context = holder.itemView.getContext();
holder.text.setText(item.getText());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = Intent(context, YourActivity.class);
intent.putExtra("item", item.getText())
context.startActivity(intent);
}
});
}
In your Other Activity, get data as:
// onCreate()
String value = getIntent().getStringExtra("item", "");

how to make the progress bar invisible in recyclerview

There is a list of pictures made through RecyclerView. When you click on a picture while it is being transferred to the next activity, a ProgressBar should be displayed. When there is a return to the activity of the image selection, the ProgressBar also remains visible, although it must be hidden.
As I did below, the progress bar becomes invisible only in the first image, but in the rest it does not work. I can’t understand why
in my project there are such classes as:
interface
public interface ImageOnC {
void onClick(int position);
}
ImageViewHolder
public class ImageViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
private ImageOnC imageOnC;
public ImageButton imageButton;
public ProgressBar progressBar;
public void setImageOnC(ImageOnC imageOnC) {
this.imageOnC = imageOnC;
}
public ImageViewHolder(#NonNull final View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_outline);
progressBar = itemView.findViewById(R.id.progr);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageOnC.onClick(getAdapterPosition());
progressBar.setVisibility(View.VISIBLE);
}
});
}
}
ImageAdabter
public class ImageAdabter extends RecyclerView.Adapter<ImageViewHolder> {
private Context mContext;
private List<Integer> listImages;
public ImageAdabter(Context mContext){
this.mContext = mContext;
this.listImages = getImages();
}
private List<Integer> getImages() {
List<Integer> results = new ArrayList<>();
results.add(R.drawable.outline1);
results.add(R.drawable.outline2);
results.add(R.drawable.outline3);
results.add(R.drawable.outline4);
results.add(R.drawable.outline5);
results.add(R.drawable.outline6);
results.add(R.drawable.outline7);
results.add(R.drawable.outline8);
results.add(R.drawable.outline9);
results.add(R.drawable.outline10);
return results;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_images,parent,false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
holder.imageView.setImageResource( listImages.get(position));
holder.setImageOnC(new ImageOnC() {
#Override
public void onClick(int position) {
Common.PICTURE_SELECTED = listImages.get(position);
mContext.startActivity(new Intent(mContext, Colorful.class));
}
});
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position, List<Object>payload){
//if so, then the progress bar only works for the first image in recyclerview
if(!payload.isEmpty()){
if(payload.get(position) instanceof Integer)
holder.progressBar.setVisibility(View.GONE);
}
else super.onBindViewHolder(holder, position, payload);
}
#Override
public int getItemCount() {
return listImages.size();
}
}
I add this to activity
private void initView() {
recyclerView = findViewById(R.id.recycle_view_images);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adabter = new ImageAdabter(this);
recyclerView.setAdapter(adabter);
}
#Override
public void onResume() {
super.onResume();
if (adabter != null) {
adabter.notifyItemChanged(position, position);
}
}
in xml file use Progress bar visibility gone

How to Implemet onClick listener insidie Recycleview to open different activities

I'm using Horizontal Recycleview to show the icon in my app. It cotains one Recycle view and one Mainactivity Class.
I'm trying to use the onClick listener method inside the adapter class but to my surprise it is not working yet all and also don't recognize intent and give cannot resolve intent symbol. so I used toast message instead but also app compile sucessfully but nothing happens.
Here is my Recycle view class
public class SnapRecyclerAdapter extends RecyclerView.Adapter<SnapRecyclerAdapter.ReyclerViewHolder> {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<Item> items;
public SnapRecyclerAdapter(Context context, ArrayList<Item> items) {
this.layoutInflater = LayoutInflater.from(context);
this.context = context;
this.items = items;
}
#Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);
return new ReyclerViewHolder(item);
}
#Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
Item item = items.get(position);
holder.image.setImageResource(item.getDrawable());
holder.appName.setText(item.getName());
}
#Override
public int getItemCount() {
return items.size();
}
class ReyclerViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
context = v.getContext();
}
private View.OnClickListener Click=new View.OnClickListener(){
#Override
public void onClick(View v) {
switch(getAdapterPosition())
{
case 1:
Toast.makeText(context, "No data available", Toast.LENGTH_SHORT).show();
}
}
};
}
}
and my Mainactivity class is
public class MainActivity extends AppCompatActivity {
private ArrayList<Item> items;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
createApps();
SnapHelper snapHelper = new GravitySnapHelper(Gravity.BOTTOM);
snapHelper.attachToRecyclerView(recyclerView);
// HORIZONTAL for Gravity START/END and VERTICAL for TOP/BOTTOM
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setHasFixedSize(true);
SnapRecyclerAdapter adapter = new SnapRecyclerAdapter(this, items);
recyclerView.setAdapter(adapter);
}
private void createApps() {
items = new ArrayList<>();
items.add(new Item("Google+", R.drawable.google_plus));
items.add(new Item("Facebook", R.drawable.facebook));
items.add(new Item("LinkedIn", R.drawable.linkedin));
items.add(new Item("Youtube", R.drawable.youtube));
items.add(new Item("Instagram", R.drawable.instagram));
items.add(new Item("Skype", R.drawable.skype));
items.add(new Item("Twitter", R.drawable.twitter));
items.add(new Item("Wikipedia", R.drawable.wikipedia));
items.add(new Item("Whats app", R.drawable.what_apps));
items.add(new Item("Pokemon Go", R.drawable.pokemon_go));
}
}
Your implementation setOnClickListener is not correct. You should set it for each view in RecylerView and inside that you can write your code to start an activity or show a toast, etc.
public class SnapRecyclerAdapter extends RecyclerView.Adapter<SnapRecyclerAdapter.ReyclerViewHolder> {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<Item> items;
public SnapRecyclerAdapter(Context context, ArrayList<Item> items) {
this.layoutInflater = LayoutInflater.from(context);
this.context = context;
this.items = items;
}
#Override
public ReyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View item = layoutInflater.inflate(R.layout.item_recycler_view, parent, false);
ReyclerViewHolder holder = new ReyclerViewHolder(item)
item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, items.get(holder.getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
// TODO: You can start an activity by using Intent as well.
}
});
return holder;
}
#Override
public void onBindViewHolder(final ReyclerViewHolder holder, int position) {
Item item = items.get(position);
holder.image.setImageResource(item.getDrawable());
holder.appName.setText(item.getName());
}
#Override
public int getItemCount() {
return items.size();
}
class ReyclerViewHolder extends RecyclerView.ViewHolder {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
context = v.getContext();
}
}
}
You want the click listener on the whole itemView? Here is an example:
//Implement View.OnClickListener
class ReyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView image;
private TextView appName;
private ReyclerViewHolder(final View v) {
super(v);
image = (ImageView) v.findViewById(R.id.image);
appName = (TextView) v.findViewById(R.id.app_name);
// Set the onClickListener
v.setOnClickListener(this)
}
#Override
public void onClick(View v) {
// if (getAdapterPosition() != RecyclerView.NO_POSITION) {
Context context = v.getContext();
Intent intent = new Intent(context, aActivityClass.class);
intent.putExtra(extraKey, extraValue);
context.startActivity(intent)
// }
};
}
Do you set the click listener on a View ? Something like image.setOnClickListener(Click) ? By the way, variables should start with lowercase
you need to pass the view from adapter by using onclickListner and make and internface in adapter
this is where we are passing the view in adapter :
#Override
public void onBindViewHolder(myholder holder, final int position) {
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.click(position,view);
}
});
Interface for adapter onclick and activity:
public void clickItem(PartnerBankAdapter.OnItemClick onItemClick){
this.onItemClick=onItemClick;
}
public interface OnItemClick{
public void click(int postion,View view);
}
Define Interface as glocbal object in adapter:
private OnItemClick onItemClick;
Consider this example for adapter:
public class PartnerBankAdapter extends RecyclerView.Adapter<PartnerBankAdapter.myholder> {
public Context mContext;
ArrayList<String> bankname;
ArrayList<Integer> iconlist;
private OnItemClick onItemClick;
public PartnerBankAdapter(Context mContext, ArrayList<String> banklist,ArrayList<Integer> iconlist)
{
this.mContext = mContext;
this.bankname=banklist;
this.iconlist=iconlist;
}
#Override
public myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.bank_list_adpater,parent,false);
return new myholder(view);
}
#Override
public void onBindViewHolder(myholder holder, final int position) {
holder.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.click(position,view);
}
});
holder.txt.setText(bankname.get(position));
holder.image.setImageResource(iconlist.get(position));
holder.txtacc.setText(bankname.get(position));
}
#Override
public int getItemCount() {
return bankname.size();
}
public static class myholder extends RecyclerView.ViewHolder {
TextView txt,txtacc;
ImageView image;
LinearLayout parent;
public myholder(View itemView) {
super(itemView);
txt= (TextView) itemView.findViewById(R.id.txbank);
image=(ImageView) itemView.findViewById(R.id.imagebank);
parent=(LinearLayout) itemView.findViewById(R.id.parent);
txtacc=(TextView) itemView.findViewById(R.id.txbankacc);
}
}
public void clickItem(PartnerBankAdapter.OnItemClick onItemClick){
this.onItemClick=onItemClick;
}
public interface OnItemClick{
public void click(int postion,View view);
}
}
and then just use onclick in your activity on recyclerview
consider code below for onclick in activity :
partnerBankAdapter.clickItem(new PartnerBankAdapter.OnItemClick() {
#Override
public void click(int postion, View view) {
}
});

Displaying recyclerView on MainActivity

I'm trying to display my recyclerView on MainActivity, but can't seem to do it.
This is my code: (which compiles with no errors)
private RecyclerView recyclerView;
private MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) this.findViewById(R.id.recycler_view_example);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapter(this, getData());
recyclerView.setAdapter(adapter);
// Add Code to display recyclerView on Main...
}
// This is not my actual data, just testing it out
public static List<Block> getData() {
List<Block> data = new ArrayList<>();
String[] ids = {"310", "313", "320"};
String[] names = {"name of three ten", "name of three thirteen", "name of three twenty"};
for (int i=0; i<ids.length; i++) {
data.add(new Block(ids[i], names[i]));
}
return data;
}
And myActivity Class:
private final LayoutInflater inflater;
// Data: (information)
List<Block> data = new ArrayList<>();
public MyAdapter(Context context, List<Block> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.block, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
MyViewHolder holder = new MyViewHolder(h.itemView);
Block current = data.get(position);
holder.id.setText(current.getId());
holder.name.setText(current.getName());
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView name;
Button button;
// Constructor
public MyViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.the_course_id);
name = (TextView) itemView.findViewById(R.id.course_name);
button = (Button) itemView.findViewById(R.id.click);
}
}
}
All I'm trying to do now is that when I run the emulator, I will see the contents of the recyclerView. But, I've been stuck on this for a while as nothing seems to work.
Mind you I'm a beginner with Android, so forgive me if this is very trivial.
You should return the number of items in your list, within getItemCount as in:
#Override
public int getItemCount() {
return data.size();
}
Ok here you need to change the following: update -
recyclerView.setLayoutManager(new LinearLayoutManager(this));
to
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
and in adapter class change:
#Override
public int getItemCount() {
return data.size();
}
thats it. Happy coding :)
Change onBindViewHolder to:
#Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {
Block current = data.get(position);
h.id.setText(current.getId());
h.name.setText(current.getName());
}
also add #SelçukCihan solution to this
EDIT
Also if you want to use your MyViewHolder you have to change the following:
First change class signature:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
and also change the signature for onBindViewHolder:
public void onBindViewHolder(MyViewHolder h, int position)
and finally change the signature of your MyViewHolder class:
static class MyViewHolder extends RecyclerView.ViewHolder

Categories