I need to make a ecommerce app type screen with multiple viewpager and recycler views.
I implemented it but my 1 out of 2 view pager is visible in recycler view and once I rotate the device, my first view pager also disappear.
My Activity:
public class MainActivity extends AppCompatActivity {
private List<ProductEntity> productEntities = new ArrayList<>();
private RecyclerView productlist;
private HomeAdapter homeAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
productlist = (RecyclerView)findViewById(R.id.mainlist);
//productlist.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
productlist.setLayoutManager(mLayoutManager);
homeAdapter = new HomeAdapter(this,getSupportFragmentManager(),productEntities);
productlist.setAdapter(homeAdapter);
new ParserJsonTask().execute();
}
public String loadJSONFromAsset() {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"f_two.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
private class ParserJsonTask extends AsyncTask<Void, Integer, List<ProductEntity>> {
#Override
protected List<ProductEntity> doInBackground(Void... params) {
try{
return JsonParser.getInstance().parseJson(loadJSONFromAsset());
}catch(Exception e){
Log.d("Exception", e.toString());
}
return null;
}
#Override
protected void onPostExecute(List<ProductEntity> result) {
Log.e("Length",""+result.size());
if(result != null) {
productEntities = result;
homeAdapter.setProduct(productEntities);
}
}
}
My view pager Fragment:
public class ImageFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_IMAGE_URL = "image_url";
private Context context;
private String image_url;
public ImageFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ImageFragment newInstance(String image) {
ImageFragment fragment = new ImageFragment();
Bundle args = new Bundle();
args.putString(ARG_IMAGE_URL, image);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
image_url = getArguments().getString(ARG_IMAGE_URL);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_image, container, false);
ImageView image = (ImageView) rootView.findViewById(R.id.image);
Log.e("Pager Item Image",""+image_url);
if(!TextUtils.isEmpty(image_url))
Picasso.with(context).load(image_url).into(image);
return rootView;
}
}
My Main adapter for recycler view:
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ProductEntity> productEntities;
private Context context;
private FragmentManager fragmentManager;
private OnItemClickListener mItemClickListener;
private static final int TYPE_FIRST = 0;
private static final int TYPE_SECOND = 1;
private static final int TYPE_THIRD = 2;
private static final String TEMPLATE_FIRST ="product-template-1";
private static final String TEMPLATE_SECOND ="product-template-2";
private static final String TEMPLATE_THIRD ="product-template-3";
public HomeAdapter(Context context , FragmentManager fragmentManager ,List<ProductEntity> productEntities) {
this.productEntities = productEntities;
this.context = context;
this.fragmentManager = fragmentManager;
}
#Override
public int getItemCount() {
Log.e("Item count",""+productEntities.size());
return productEntities.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof ImageViewHolder) {
ImageViewHolder imageViewHolder = (ImageViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
Log.e("Template Item Image",""+productEntity.getItemEntities().get(0).getImage());
Picasso.with(context).load(productEntity.getItemEntities().get(0).getImage()).into(imageViewHolder.imageView);
} else if(holder instanceof PagerViewHolder) {
PagerViewHolder pagerViewHolder = (PagerViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
pagerViewHolder.viewPager.setAdapter(new PagerAdapter(fragmentManager,productEntity.getItemEntities()));
} else if (holder instanceof HorizontalViewHolder) {
HorizontalViewHolder horizontalViewHolder = (HorizontalViewHolder) holder;
ProductEntity productEntity = productEntities.get(position);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
horizontalViewHolder.recyclerView.setLayoutManager(linearLayoutManager);
horizontalViewHolder.recyclerView.setAdapter(new SliderAdapter(context,productEntity.getItemEntities()));
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if(viewType == TYPE_FIRST) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_image, parent, false);
return new ImageViewHolder (v);
} else if(viewType == TYPE_SECOND) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_horizontal, parent, false);
return new HorizontalViewHolder (v);
} else {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.content_pager, parent, false);
return new PagerViewHolder(v);
}
}
#Override
public int getItemViewType (int position) {
if(productEntities.get(position).getTemplate().equalsIgnoreCase(TEMPLATE_FIRST)) {
Log.e("Item type",""+TYPE_FIRST);
return TYPE_FIRST;
} else if(productEntities.get(position).getTemplate().equalsIgnoreCase(TEMPLATE_SECOND)) {
Log.e("Item type",""+TYPE_SECOND);
return TYPE_SECOND;
} else {
Log.e("Item type",""+TYPE_THIRD);
return TYPE_THIRD;
}
}
class PagerViewHolder extends RecyclerView.ViewHolder {
protected ViewPager viewPager;
public PagerViewHolder (View itemView) {
super (itemView);
this.viewPager = (ViewPager) itemView.findViewById (R.id.viewpager);
}
}
class ImageViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
public ImageViewHolder (View itemView) {
super (itemView);
this.imageView = (ImageView) itemView.findViewById (R.id.image);
}
}
public class HorizontalViewHolder extends RecyclerView.ViewHolder {
protected RecyclerView recyclerView;
public HorizontalViewHolder(View v) {
super(v);
recyclerView = (RecyclerView)v.findViewById(R.id.horizontallist);
}
}
public void setProduct(List<ProductEntity> data) {
productEntities.clear();
productEntities.addAll(data);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
My view pager adapter:
public class PagerAdapter extends FragmentPagerAdapter {
private List<ItemEntity> itemEntities;
public PagerAdapter(FragmentManager fm, List<ItemEntity> itemEntities) {
super(fm);
this.itemEntities = itemEntities;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return ImageFragment.newInstance(itemEntities.get(position).getImage());
}
#Override
public int getCount() {
// Show 3 total pages.
return itemEntities.size();
}
}
My horizontal recyclerview adapter:
public class SliderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ItemEntity> itemEntities;
private Context context;
private OnItemClickListener mItemClickListener;
public SliderAdapter(Context context , List<ItemEntity> notesEntities) {
this.itemEntities = notesEntities;
this.context = context;
}
#Override
public int getItemCount() {
return itemEntities.size();
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
ItemEntity itemEntity = itemEntities.get(position);
itemViewHolder.productName.setText(itemEntity.getLabel());
Log.e("Item Image",""+itemEntity.getImage());
if(!TextUtils.isEmpty(itemEntity.getImage()))
Picasso.with(context).load(itemEntity.getImage()).into(itemViewHolder.productImage);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.recycler_card_layout, parent, false);
return new ItemViewHolder (v);
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
protected TextView productName;
protected ImageView productImage;
public ItemViewHolder(View v) {
super(v);
productName = (TextView) v.findViewById(R.id.product_name);
productImage = (ImageView) v.findViewById(R.id.product_image);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mItemClickListener != null)
mItemClickListener.onItemClick(v, getAdapterPosition());
}
});
}
}
public void setItems(List<ItemEntity> data) {
itemEntities.clear();
itemEntities.addAll(data);
notifyDataSetChanged();
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
Main activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activity.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/mainlist"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Horizontal scrolling layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activity.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/horizontallist"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
View pager layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="200dp">
</android.support.v4.view.ViewPager>
</RelativeLayout>
As per my JSON data, it should have 2 view pager inside recycler view and but it is showing only 1 in portrait mode and once I rotate the device, both are disappear. I thing data is not visible inside recycler view as I can see white space in recycler view while scrolling.
Any help would be appreciated.
Simple change :
extends FragmentPagerAdapter
to
extends FragmentStatePagerAdapter
Related
I have a nested recyclerview to show the list of foods in each category. When the user clicks the increase or decrease button, the quantity will be updated to the quantity textview and synced to the cart stored in the database, but currently I don't know how to listen for the event when the user clicks these buttons.
Here is my current UI when run:
enter image description here
Here is my fragment:
public class TabOrderFragment extends Fragment {
private static final String ARG_RESTAURANT_ID = "restaurantId";
private int restaurantId;
View view;
RecyclerView menuRecyclerView;
RecyclerView.LayoutManager layoutManager;
ArrayList<Menu> menuArrayList;
MenuAdapter menuAdapter;
public TabOrderFragment() { }
public static TabOrderFragment newInstance(int restaurantId) {
TabOrderFragment fragment = new TabOrderFragment();
Bundle args = new Bundle();
args.putInt(ARG_RESTAURANT_ID, restaurantId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
restaurantId = getArguments().getInt(ARG_RESTAURANT_ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tab_order, container, false);
if(restaurantId != 0) {
DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getActivity());
menuArrayList = new ArrayList<Menu>();
menuArrayList = databaseHandler.getAllMenuFoodsByIdRestaurant(restaurantId);
menuRecyclerView = view.findViewById(R.id.rcv_foods_menu);
menuAdapter = new MenuAdapter(getActivity().getApplicationContext(), restaurantId);
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
menuRecyclerView.setLayoutManager(layoutManager);
menuAdapter.setData(menuArrayList);
menuRecyclerView.setAdapter(menuAdapter);
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("TabOrderFragment", "Restaurant Id = " + restaurantId);
}
Here is my MenuAdapter:
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
Context context;
private int restaurantId;
private RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
ArrayList<Menu> menuList;
public MenuAdapter(ArrayList<Menu> menuList) {
this.menuList = menuList;
}
public MenuAdapter(Context context, int restaurantId) {
this.context = context;
this.restaurantId = restaurantId;
}
public void setData(ArrayList<Menu> menuList) {
this.menuList = menuList;
notifyDataSetChanged();
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_foods_menu, parent, false);
return new MenuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MenuViewHolder holder, int position) {
Menu menu = menuList.get(position);
holder.txtMenuTitle.setText(menu.getTitle().concat(" (" + String.valueOf(menu.getQuantity()) + ")"));
LinearLayoutManager layoutManager = new LinearLayoutManager(holder.rcvListFoods.getContext(), LinearLayoutManager.VERTICAL, false);
layoutManager.setInitialPrefetchItemCount(menu.getFoods().size());
FoodAdapter foodAdapter = new FoodAdapter(menu.getFoods(), restaurantId);
holder.rcvListFoods.setLayoutManager(layoutManager);
holder.rcvListFoods.setAdapter(foodAdapter);
holder.rcvListFoods.setRecycledViewPool(viewPool);
}
#Override
public int getItemCount() {
if(menuList != null) {
return menuList.size();
}
return 0;
}
public class MenuViewHolder extends RecyclerView.ViewHolder {
private TextView txtMenuTitle;
private RecyclerView rcvListFoods;
public MenuViewHolder(#NonNull View itemView) {
super(itemView);
txtMenuTitle = itemView.findViewById(R.id.txv_menu_title);
rcvListFoods = itemView.findViewById(R.id.rcv_list_foods);
}
}
}
Here is my FoodAdapter:
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private ArrayList<Food> foodList;
private int restaurantId;
private int userId;
SharedPreferences sharedPreferences;
public FoodAdapter(ArrayList<Food> foodList, int restaurantId) {
this.foodList = foodList;
this.restaurantId = restaurantId;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
sharedPreferences = fragmentActivity.getSharedPreferences("currentUser", Context.MODE_PRIVATE);
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_food, parent, false);
return new FoodViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) {
Food food =foodList.get(position);
Picasso.get().load(food.getThumbImage()).into(holder.foodThumbImage);
holder.foodName.setText(food.getName());
holder.foodDescription.setText(food.getDescription());
double price = Double.parseDouble(food.getPrice());
DecimalFormat formatter = new DecimalFormat("#,###");
holder.foodPrice.setText(formatter.format(price) + "đ");
}
#Override
public int getItemCount() {
if(foodList != null) {
return foodList.size();
}
return 0;
}
public class FoodViewHolder extends RecyclerView.ViewHolder {
private ImageView foodThumbImage;
private TextView foodName;
private TextView foodDescription;
private TextView foodPrice;
private TextView quantity;
private MaterialButton increaseBtn;
private MaterialButton decreaseBtn;
private ItemClickListener itemClickListener;
public FoodViewHolder(#NonNull View itemView) {
super(itemView);
foodThumbImage = itemView.findViewById(R.id.image_food);
foodName = itemView.findViewById(R.id.txv_food_name);
foodDescription = itemView.findViewById(R.id.txv_food_description);
foodPrice = itemView.findViewById(R.id.txv_food_price);
quantity = itemView.findViewById(R.id.txv_quantity);
increaseBtn = itemView.findViewById(R.id.btn_increase);
decreaseBtn = itemView.findViewById(R.id.btn_decrease);
}
}
in your food adapter's onBindViewHolder method use
holder.increaseBtn.setOnClickListener{
onIncreaseClick()
}
while create an interface like
interface Listener{
public void onIncreaseClick();
public void onDecreaseClick();
}
and implement your interface in your activity or fragment or viewmodel where you can listen for the click event
What you can do generally when you have something like that, is to create an interface for the interaction with the Recycler view:
interface Interaction {
public void onFoodClick(Food food)
}
Then you add an instance of this interface in your recycler view adapter, and you let your activity or fragment implement this interface, please find a good explanation here: https://stackoverflow.com/a/31671289/7334951
I have follow view structure:
<RecyclerView>
<CardView>
<RecyclerView id:="inner_recycler">
</RecyclerView>
</CardView>
<CardView>
<ViewPager id:="pager_1">
</ViewPager>
</CardView>
<CardView>
<ViewPager id:="pager_2">
</ViewPager>
</CardView>
<CardView>
<ViewPager id:="pager_3">
</ViewPager>
</CardView>
</RecyclerView>
RecyclerView adapter:
public class TodayStatsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Map<Date, StatsBean> mStats;
private Context mContext;
public TodayStatsAdapter(Context context, Map<Date, StatsBean> stats) {
mStats = stats;
mContext = context;
}
#Override
public int getItemViewType(int position) {
if (position > 0) {
return R.layout.today_stats_other_item;
} else {
return R.layout.today_stats_first_item;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
if (R.layout.today_stats_first_item == viewType) {
return new TodayFirstStatsHolder(view);
} else {
return new TodayOtherStatsHolder(view, mContext);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
List<Date> listDate = new ArrayList<>(mStats.keySet());
Collections.sort(listDate, Date::compareTo);
if (holder instanceof TodayFirstStatsHolder) {
TodayFirstStatsHolder viewHolder = (TodayFirstStatsHolder) holder;
final Date lastDate = listDate.get(listDate.size() - 1);
final StatsBean bean = mStats.get(lastDate);
viewHolder.setDateTime(mContext.getString(R.string.stats_today_text)+ " " + lastDate.getHours() + ":" + lastDate.getMinutes());
viewHolder.initRecycler(bean);
}
if (holder instanceof TodayOtherStatsHolder) {
TodayOtherStatsHolder viewHolder = (TodayOtherStatsHolder) holder;
final Date lastDate = listDate.get(position - 1);
final StatsBean bean = mStats.get(lastDate);
viewHolder.setDateTime(mContext.getString(R.string.stats_today_text)+ " " + lastDate.getHours() + ":" + lastDate.getMinutes());
viewHolder.initPager(bean);
}
}
#Override
public int getItemCount() {
return mStats.size();
}
public static class TodayFirstStatsHolder extends RecyclerView.ViewHolder {
private TextView mItemDateText;
private RecyclerView mItemRecyclerView;
private Context mContext;
public TodayFirstStatsHolder(#NonNull View itemView) {
super(itemView);
mContext = itemView.getContext();
mItemDateText = itemView.findViewById(R.id.first_item_date_text);
mItemRecyclerView = itemView.findViewById(R.id.first_item_recycler_view);
}
public void setDateTime(String dateTime) {
mItemDateText.setText(dateTime);
}
public void initRecycler(StatsBean bean) {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext) {
#Override
public boolean canScrollVertically() {
return false;
}
};
mItemRecyclerView.setLayoutManager(layoutManager);
mItemRecyclerView.setHasFixedSize(true);
TodayStatsFirstItemAdapter adapter = new TodayStatsFirstItemAdapter(bean, mContext);
mItemRecyclerView.setAdapter(adapter);
}
}
public static class TodayOtherStatsHolder extends RecyclerView.ViewHolder {
private TextView mItemDateText;
private ViewPager mItemViewPager;
private Context mContext;
public TodayOtherStatsHolder(#NonNull View itemView, Context context) {
super(itemView);
mContext = context;
mItemDateText = itemView.findViewById(R.id.first_item_date_text);
mItemViewPager = itemView.findViewById(R.id.other_item_pager);
mItemViewPager.setVisibility(View.VISIBLE);
}
public void setDateTime(String dateTime) {
mItemDateText.setText(dateTime);
}
public void initPager(StatsBean bean) {
TodayStatsOtherItemPagerAdapter pagerAdapter = new TodayStatsOtherItemPagerAdapter(
((MainActivity) mContext).getSupportFragmentManager(),
bean.getStats()
);
mItemViewPager.setAdapter(pagerAdapter);
}
}
}
PagerAdapter:
public class TodayStatsOtherItemPagerAdapter extends FragmentStatePagerAdapter {
private final List<Map.Entry<String, Integer>> mEntriesStats;
public TodayStatsOtherItemPagerAdapter(FragmentManager fm, Map<String, Integer> stats) {
super(fm);
mEntriesStats = new ArrayList<>(stats.entrySet());
}
#Override
public Fragment getItem(int position) {
return TodayStatsPagerFragment.newInstance(mEntriesStats.get(position));
}
#Override
public int getCount() {
return mEntriesStats.size();
}
}
The first RecyclerView has an adapter which creating CardView with a RecyclerView or a ViewPager. The inner RecyclerView is initializing and working normally. Every ViewPagers have own PagerAdapters and ViewHolders. The "pager_1" is creating and inflating normally but other pagers don't attached own adapters and therefore don't show information. Why did adapters demonstrate such behavior? How to do that every ViewPager will attach own adapter?
Sorry for my bad English. I hope you will help me.
I have a fragment that is suppose to display the results of my alert dialog in my RecyclerView. Every time I click the "ADD" in my dialog, it adds duplicated results to my RecyclerView. I've searched and searched but cannot seem to find what I am doing wrong. I've tried adding .clear(); but if I add that, nothing shows up in my RecyclerView at all. I've added in my adapter getItemId and getItemViewType to return position; but the items still get duplicated. I've added adapter.setData(model) followed by adapter.notifyDataSetChange(); and my RecyclerView still shows duplicated items. The app runs so I have no logcat to post. Thank you.
Model
public class SubjectsModel
{
//private long id;
private String mTitle;
private String mTeacher;
public String getmTitle()
{
return mTitle;
}
public void setmTitle(String title)
{
this.mTitle = title;
}
public String getmTeacher()
{
return mTeacher;
}
public void setmTeacher(String teacher)
{
this.mTeacher = teacher;
}
}
Fragment
public class SubjectsFrag extends DialogFragment implements
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public RecyclerSubAdapter recyclerSubAdapter;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper helper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
helper = new DbHelper(getActivity());
helper.getSubject();
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerSubAdapter = new RecyclerSubAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerSubAdapter);
return view;
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel();
model.setmTitle(title);
model.setmTeacher(teacher);
//subMod.clear();
subMod.add(model);
recyclerSubAdapter.setData(subMod);
recyclerSubAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Adapter
public class RecyclerSubAdapter extends RecyclerView.Adapter<RecyclerSubAdapter.ViewHolder>
{
private static final String TAG = RecyclerSubAdapter.class.getSimpleName();
public List<SubjectsModel> subMod = new ArrayList<>();
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
DbHelper helper;
public RecyclerSubAdapter(Context context, ArrayList<SubjectsModel> subMod)
{
this.context = context;
this.subMod = subMod;
this.helper = new DbHelper(context);
}
#NonNull
#Override
public RecyclerSubAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.subjects_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerSubAdapter.ViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
//helper.addClass(subMod.get(position));
}
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public ViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
}
}
}
#Override
public int getItemCount()
{
if (subMod == null)
{
Log.d(TAG, "sub is null");
}
return subMod.size();
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemViewType(int position)
{
return position;
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
RecyclerSubAdapter.clickListener = clicked;
}
public interface ClickListener
{
void itemClicked(SubjectsModel model, int position);
}
public void setData(ArrayList<SubjectsModel> data)
{
this.subMod = data;
//this.subMod.clear();
this.subMod.addAll(data);
notifyDataSetChanged();
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
In OnAddSubjectSubmit() you call subMod.add(model);
and then you call recyclerSubAdapter.setData(subMod); which in turn calls this.subMod.addAll(data);.
Check it yourself. I believe it's there where you add the new item twice.
Suggestion: comment out recyclerSubAdapter.setData(subMod); from OnAddSubjectSubmit().
this.subMod = data;
this.subMod.addAll(data);
You initilize subMod by assigning data to it, and later you add data again:
this.subMod.addAll(data);
In my app I have 15 cardview's ,Now I want to show a fragment when I clicked the cardview's for that I have 15 fragments.
RecyclerViewAdapter.java
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
private Context mContext;
private List<reminder> mData;
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (getAdapterPosition()) {
case 0 :
// "What Should I do here"
}
}
});
}
}
}
Reminders.java
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
lstreminder = new ArrayList<>();
lstreminder.add(new reminder("Alarm",R.drawable.alarms));
lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
lstreminder.add(new reminder("Call / SMS",R.drawable.call));
lstreminder.add(new reminder("Recharges",R.drawable.recharges));
lstreminder.add(new reminder("Meetings",R.drawable.meetings));
lstreminder.add(new reminder("Insurance",R.drawable.insurances));
lstreminder.add(new reminder("Exams",R.drawable.exams));
lstreminder.add(new reminder("Holidays",R.drawable.holidays));
lstreminder.add(new reminder("Medical",R.drawable.medical));
lstreminder.add(new reminder("Purchase",R.drawable.purchase));
lstreminder.add(new reminder("Travel",R.drawable.travel));
lstreminder.add(new reminder("Shows",R.drawable.shows));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
#Override
public void onClick(reminder str) {
}
});
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(recyclerviewAdapter);
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Image
here in switch case I want to open new fragments based on the adapter's position.
Is it possible please guide me to solve ,Or if I am in wrong path please guide me ...
make interface in recycler view adapter like below code..
onItemClickListner onItemClickListner;
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(String str);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
String data=mStringList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
Your Code ..
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyViewHolder> {
private Context mContext;
private List<reminder> mData;
onItemClickListner onItemClickListner;
public void setOnItemClickListner(onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(reminder str);//pass your object types.
}
public RecyclerviewAdapter(Context mContext, List<reminder> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.cardview, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
reminder data=mData.get(position);
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
}
}
}
then after define adapter value and bind into recycler view call below code.. in activity when bind adapter into recycler view.
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
#Override
public void onClick(String str) {
// here call your fragment
}
});
your code for fragment..
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
List<reminder> lstreminder;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
lstreminder = new ArrayList<>();
lstreminder.add(new reminder("Alarm",R.drawable.alarms));
lstreminder.add(new reminder("Birthday",R.drawable.birthdays));
lstreminder.add(new reminder("Anniversary",R.drawable.anniversaries));
lstreminder.add(new reminder("Buy Gifts",R.drawable.buygift));
lstreminder.add(new reminder("Bill Payments",R.drawable.billpayments));
lstreminder.add(new reminder("Call / SMS",R.drawable.call));
lstreminder.add(new reminder("Recharges",R.drawable.recharges));
lstreminder.add(new reminder("Meetings",R.drawable.meetings));
lstreminder.add(new reminder("Insurance",R.drawable.insurances));
lstreminder.add(new reminder("Exams",R.drawable.exams));
lstreminder.add(new reminder("Holidays",R.drawable.holidays));
lstreminder.add(new reminder("Medical",R.drawable.medical));
lstreminder.add(new reminder("Purchase",R.drawable.purchase));
lstreminder.add(new reminder("Travel",R.drawable.travel));
lstreminder.add(new reminder("Shows",R.drawable.shows));
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.mRecyclerView_id);
RecyclerviewAdapter recyclerviewAdapter = new RecyclerviewAdapter(getActivity(),lstreminder);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(recyclerviewAdapter);
recyclerviewAdapter.setOnItemClickListner(new RecyclerviewAdapter.onItemClickListner() {
#Override
public void onClick(reminder str) {
// here str is click item value in recyclerview.
// here perform your operation . str is give object reminder pojo class of selected item on recyclerview.
// below code you can make condition and check any value.
if(str.getItemName().equals("xyz")){
Fragment fragment = new MainFragment();// here give your fragment.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
else if(str.getItemName().equals("ayx")){
Fragment fragment = new HomeFragment();// here give your fragment.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
recyclerviewAdapter.notifyDataSetChanged();
}
});
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Try like this:
public class NewAdapter extends RecyclerView.Adapter<NewAdapter.MyViewHolder> {
Context context;
LayoutInflater inflater;
Activity activity;
View view;
RecyclerView recyclerViewNew;
private ArrayList<reminder> mData;
public NewAdapter(RecyclerView recyclerView, Context context, ArrayList<reminder>
mData, Activity activity) {
this.context = context;
this.mData = mData;
this.activity = activity;
inflater = LayoutInflater.from(this.context);
this.recyclerViewNew = recyclerView;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_cases_fragment, parent, false);
MyViewHolder sectionViewHolder = new MyViewHolder(view);
return sectionViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final int pos = position;
holder.mTextView.setText(mData.get(position).getmTitle());
holder.mImageView.setImageResource(mData.get(position).getmImages());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = view.getContext();
Intent intent = new Intent();
switch (pos) {
case 0:
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
break;
}
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ImageView mImageView;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.mReminder_Text_Id);
mImageView = (ImageView) itemView.findViewById(R.id.mReminder_Image_Id);
cardView = (CardView) itemView.findViewById(R.id.cardView);
}
}
}
Hope this helps you.
I have one query related to RecyclerView. I want to get clicked items and set it to textview in the same layout then after that set the values to textview, update the adapter.
This is my recyclerview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/rl_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imageView_flag"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:src="#drawable/usa" />
<TextView
android:id="#+id/textview_currency_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 USD(United States of America)"
android:layout_centerVertical="true"
android:textColor="#000"
android:layout_toEndOf="#+id/imageView_flag"
android:layout_marginStart="14dp" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_exchange_rate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/rl_container"/>
</RelativeLayout>
This is my fragment class:
public class ExchangeRatesFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
private String mParam1;
private String mParam2;
RetrofitClient retrofitClient;
RestInterface service;
ArrayList<ExchangeRate> exchangeRatesArraylist;
private RecyclerView mRecyclerView;
private ExchangeRateAdapter exchangeRateAdapter;
TextView textview_currency_info;
ImageView imageView_flag;
public ExchangeRatesFragment() {}
public static ExchangeRatesFragment newInstance(String param1, String param2) {
ExchangeRatesFragment fragment = new ExchangeRatesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_exchange_rates, container, false);
exchangeRatesArraylist = new ArrayList<>();
retrofitClient = new RetrofitClient();
service = retrofitClient.getAPIClient(WebServiceUrls.DOMAIN_MAIN);
textview_currency_info = (TextView) rootView.findViewById(R.id.textview_currency_info);
imageView_flag = (ImageView) rootView.findViewById(R.id.imageView_flag);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_exchange_rate);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
get_exchange_rate("USD");
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public void get_exchange_rate(String from){
service.exchange_rate(from, new Callback<JsonElement>() {
#Override
public void success(JsonElement jsonElement, Response response) {
//this method call if webservice success
try {
JSONObject jsonObject = new JSONObject(jsonElement.toString());
final JSONArray exchange_rate = jsonObject.getJSONArray("exchange_rate");
for(int i=0; i<exchange_rate.length(); i++){
JSONObject currencyNews = exchange_rate.getJSONObject(i);
String short_name = currencyNews.getString("short_name");
String full_name = currencyNews.getString("full_name");
String flag = currencyNews.getString("flag");
String chang_value =currencyNews.getString("chang_value");
ExchangeRate currencyConverter = new ExchangeRate(short_name, full_name, flag, chang_value);
exchangeRatesArraylist.add(currencyConverter);
}
exchangeRateAdapter = new ExchangeRateAdapter(getContext(), exchangeRatesArraylist);
mRecyclerView.setAdapter(exchangeRateAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(),"Please check your internet connection", Toast.LENGTH_LONG ).show();
}
});
}
This is my adapter class:
public class ExchangeRateAdapter extends RecyclerView.Adapter<ExchangeRateAdapter.ViewHolder>{
private ArrayList<ExchangeRate> mArrayList;
private Context context;
private final LayoutInflater mInflater;
public ExchangeRateAdapter(Context context, ArrayList<ExchangeRate> arrayList) {
this.mInflater = LayoutInflater.from(context);
mArrayList = arrayList;
context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.exchange_rate_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
holder.relativeLayout.setOnClickListener(clickListener);
holder.textView_full_name.setTag(holder);
holder.textView_short_name.setText(mArrayList.get(i).getShort_name());
holder.textView_full_name.setText(mArrayList.get(i).getFull_name());
holder.textview_currency_value.setText(mArrayList.get(i).getChang_value());
Picasso.with(context).load("http://uploads/country_flag/"+ mArrayList.get(i).getFlag()).into(holder.imageView_flag);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
int position = holder.getPosition();
ExchangeRate person = mArrayList.get(position);
String businessids = person.getFull_name();
Intent intent = new Intent(context, test.class);
intent.putExtra("businessids", businessids);
context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return mArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView textView_short_name, textView_full_name, textview_currency_value;
private ImageView imageView_flag;
RelativeLayout relativeLayout;
ViewHolder(View itemView) {
super(itemView);
textView_short_name = (TextView)itemView.findViewById(R.id.textView_short_name);
textView_full_name = (TextView)itemView.findViewById(R.id.textView_full_name);
imageView_flag = (ImageView) itemView.findViewById(R.id.imageView_flag);
textview_currency_value = (TextView)itemView.findViewById(R.id.textview_currency_value);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.rl);
}
}
}
I have tried many options which published on SO but I didn't any solution. How to solve this query? When I set the onclicklistener to ViewHolder so I'm getting the position values only -1 on every item clicklistener.
A few things:
You are setting a tag on "holder.textView_full_name.setTag(holder)" while you are getting the tag from the view which was clicked (which would be the relative layout, as that is where you set the click listener (holder.relativeLayout.setOnClickListener(clickListener);)
This isn't necessary anyways.
In your click listener, call 'getAdapterPosition()', which should return what you are expecting.
Edit: Codepath has a nice overview of the RecyclerView, a little dated, but still relevant.
You can use this dependencies
implementation 'io.reactivex:rxjava:1.2.1'
implementation 'io.reactivex:rxandroid:1.2.1'
Just for example:
Reference
as with this you can click on RecyclerView
adapter.busNoItemClick().doOnNext(this::getBusNum).subscribe();
private void getBusNum(String busNo){
((TextView)findViewById(R.id.txtBusNumberStudent)).setText(busNo);
}
in adapter you have to write this:
#Override
public void onBindViewHolder(AdapterBusRouteParent.ViewHolder holder, int position) {
holder.busNumber.setOnClickListener(view -> publishSubject.onNext(busRouteParents.get(position)));
}
public Observable<String>busNoItemClick(){
return publishSubject.observeOn(AndroidSchedulers.mainThread());
}
Hope this might help you.
One way would be to have a
Variable which stores the selected item,
Set OnClickistener to the ItemView,
In the OnClickListener, set the SELECTED_INDEX as getAdapterPosition() and notify the adapter.
In the onBindViewHolder method, check if current position is equal to SELECTED_INDEX and implement the required steps.
:
int SELECTED_INDEX = 0;
public void setSelectedItemIndex(int position){
SELECTED_INDEX = position;
/*if(adapterCallback!=null) { //If you have a callback interface
adapterCallback.onItemClick(position);
}*/
notifyDataSetChanged();
}
Holder Class:
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//Item Declarations
public MyViewHolder(View itemView) {
super(itemView);
//View Binding
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v==itemView){
setSelectedItemIndex(getAdapterPosition());
}
}
}
In onBindViewHolder method:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position==SELECTED_INDEX){
//Implement your steps
}
else{
//Default Value
}
}
Hope it helps!