ViewPager2 is scrolling to the wrong page when I am selecting a tab from a far position. Swiping and selecting tab of loaded pages working fine. The error is only happening when the page is not loaded and scrolling animation is active. I have created a large viewpager2 with 100 pages containing Recyclerview.
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = findViewById(R.id.tabLayout);
ViewPager2 viewPager = findViewById(R.id.viewPager2);
viewPager.setAdapter(new viewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager, true, true,
((tab, position) -> tab.setText("Page: " + position))).attach();
}
private class viewPagerAdapter extends FragmentStateAdapter {
public viewPagerAdapter(FragmentActivity fa) {
super(fa);
}
#Override
public Fragment createFragment(int position) {
Fragment fragment = new itemFragment();
Bundle args = new Bundle();
args.putInt(itemFragment.ARG_PARAM1, position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getItemCount() {
return 100;
}
}
}
My Fragment
public class itemFragment extends Fragment {
public static final String ARG_PARAM1 = "parram1";
int pagePosition;
public itemFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pagePosition = getArguments().getInt(ARG_PARAM1);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frgment_item, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = view.findViewById(R.id.textView);
textView.setText("Page - " + pagePosition);
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setAdapter(new myAdapter());
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 16));
}
private class myAdapter extends RecyclerView.Adapter<Myvh> {
#Override
public Myvh onCreateViewHolder(ViewGroup parent, int viewType) {
return new Myvh(new TextView(getContext()));
}
#Override
public void onBindViewHolder(Myvh holder, int position) {
int codepoint=pagePosition*700 + position;
char[] ch=Character.toChars(codepoint);
holder.textView.setText(String.valueOf(ch));
}
#Override
public int getItemCount() { return 700; }
}
private class Myvh extends RecyclerView.ViewHolder {
TextView textView;
public Myvh(View itemView) {
super(itemView);
textView = (TextView) itemView;
}
}
}
I have also tried Recyclerview adapter instead of FragmentStateAdapter and getting same problem.
I have found some solution but not sufficient.
Those are:
Using old ViewPager(deprecated)
Using viewPager.setOffscreenPageLimit(100); (taking huge time to load activity)
Disabling smoothscroll ( looks awful when swiping)
Related
I tried to add Viewpager inside RecycleView item, then I created the adapter for the recycle view and I created a Pager Adapter that extends from FragmentStatePagerAdapter class inside the the adapter.
Just the first item of the recycle works fine, but the rest items of recycle view do not show the view pager.
When I Log inside the Pager Adapter I can see all the fragment position.
When I scroll horizontally inside any pager of any recycle view item I can see the Log statement, but nothing appear on the screen.
Could any one help me in that case ?
Here is my code
public class RentCategoryItemAdapter extends RecyclerView.Adapter<RentCategoryItemAdapter.ViewHolder> {
Context mContext;
ArrayList<RentCategoryItem> categoryItems;
ArrayList<MyPagerAdapter> pagerAdapters = new ArrayList<>();
/*ArrayList<ViewPager> pagerArrayList = new ArrayList<>();
ArrayList<MyPagerAdapter> myPagerAdapterArrayList = new ArrayList<>();*/
public RentCategoryItemAdapter(Context context, ArrayList<RentCategoryItem> categoryItems) {
mContext = context;
this.categoryItems = categoryItems;
AppCompatActivity activity = (AppCompatActivity) mContext;
for (int i = 0; i < categoryItems.size(); i++) {
pagerAdapters.add(new MyPagerAdapter(activity.getSupportFragmentManager(), categoryItems.get(i).catItems));
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView;
itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.rent_category_item,parent, false);
RentCategoryItemAdapter.ViewHolder viewHolder = new RentCategoryItemAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.catName.setText(categoryItems.get(position).catName);
//AppCompatActivity activity = (AppCompatActivity) mContext;
//holder.mPagerAdapter = new MyPagerAdapter(activity.getSupportFragmentManager(), categoryItems.get(position).catItems);
holder.pager.setAdapter(pagerAdapters.get(position));
Log.d("Tag", pagerAdapters.get(position).getCount() + " position " + position);
/*holder.mPagerAdapter = myPagerAdapterArrayList.get(position);
holder.pager.setAdapter(myPagerAdapterArrayList.get(position));*/
int margin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10*16, mContext.getResources().getDisplayMetrics());
holder.pager.setPageMargin(-margin);
}
#Override
public int getItemCount() {
return categoryItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private PagerAdapter mPagerAdapter;
TextView catName;
ViewPager pager;
public ViewHolder(View itemView) {
super(itemView);
pager = itemView.findViewById(R.id.pager);
catName = itemView.findViewById(R.id.cat_name);
/*pagerArrayList.add(new ViewPager(mContext));
AppCompatActivity activity = (AppCompatActivity) mContext;
myPagerAdapterArrayList.add(new MyPagerAdapter(activity.getSupportFragmentManager()));*/
}
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<RentItem> items;
public MyPagerAdapter(FragmentManager fm, ArrayList<RentItem> items) {
super(fm);
this.items = items;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new RentCategoryForPagerFragment();
Bundle bundle = new Bundle();
bundle.putString("first_last", "first");
bundle.putString("product_id", items.get(position).productId);
bundle.putString("product_name", items.get(position).productName);
bundle.putString("product_price", items.get(position).productPrice);
bundle.putString("product_image", items.get(position).productImage);
fragment.setArguments(bundle);
Log.d("Tag", "inside my pager adapter " + position);
return fragment;
}
#Override
public int getCount() {
return items.size();
}
}
}
And here is RentCategoryForPagerFragment class
public class RentCategoryForPagerFragment extends Fragment {
String firstOrLast = "";
ImageView productImage;
TextView productName, productPrice;
String productId;
Button showDetailsButton;
public RentCategoryForPagerFragment() {
//firstOrLast = getArguments().getString("first_last");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rent_item_in_category_layout, container, false);
productImage = rootView.findViewById(R.id.product_image);
productName = rootView.findViewById(R.id.product_name);
productPrice = rootView.findViewById(R.id.product_price);
showDetailsButton = rootView.findViewById(R.id.show_details_button);
Bundle bundle = getArguments();
String imageURL = bundle.getString("product_image");
Glide.with(getActivity()).load(imageURL).into(productImage);
productId = bundle.getString("product_id");
productName.setText(bundle.getString("product_name"));
productPrice.setText(bundle.getString("product_price"));
showDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked ", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
The result I got in this
Finally I found the solution. I was using the wrong class because it sound that FragmentStatePagerAdapter and FragmentPagerAdapter Classes do not serve my idea.
So You should extend from PagerAdapter instead to implement more than one pager in the same screen. And you should override some methods to complete it.
I hope this answer helps someone in someday.
I wanted to use recyclerview inside a fragment of my 3 fragment viewpager. I wrote the code and it ran perfectly but I don't know why it is too slow.When I swap from one fragment to another it almost takes half minute.Don't know what mistakes I did here.
Main Activity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.toolBar);
tabLayout = (TabLayout)findViewById(R.id.tabs);
viewPager = (ViewPager)findViewById(R.id.viewPager);
setSupportActionBar(toolbar);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(new OneFragment(), "One");
viewPagerAdapter.addFragment(new TwoFragment(), "Two");
viewPagerAdapter.addFragment(new ThreeFragment(), "Three");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
Here it is one of my fragment where I tried to implement recyclerview.
Fragment
public class TwoFragment extends Fragment {
public TwoFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_two, container, false);
OurData ourData = new OurData();
ourData.pic.add(R.drawable.b);
ourData.title.add("Hello");
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.listRecyclerView);
ListAdapter listAdapter = new ListAdapter();
recyclerView.setAdapter((listAdapter));
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
public class ListAdapter extends RecyclerView.Adapter {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((ListViewHolder) holder).bindView(position);
}
#Override
public int getItemCount() {
return OurData.title.size();
}
private class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView text;
private ImageView image;
public ListViewHolder(View itemview) {
super(itemview);
text = (TextView) itemview.findViewById(R.id.textF);
image = (ImageView) itemview.findViewById(R.id.imageF);
itemview.setOnClickListener(this);
}
public void bindView(int position) {
text.setText(OurData.title.get(position));
image.setImageResource(OurData.pic.get(position));
}
public void onClick(View view) {
}
}
}
public class OurData {
public static ArrayList<String> title = new ArrayList<String>();
public static ArrayList<Integer> pic = new ArrayList<Integer>();
}
It tooks my whole day thinking what I did wrong. Please help me out!
set your adapter recyclerView.setAdapter((listAdapter));
insise onViewCreated instead of onCreateView
I think the problem is because of one of your Methods.
maybe 'OurData'
and also are you sure of this:
#Override
public int getItemCount() {
return OurData.title.size();
}
also try using Log in each code and see the part that takes time especially 'OurData'
i'm facing an issue i can't seem to resolve and i'd like some help.
My app is composed by an activity containing a fragment. After the user taps on a suggestion, activity's method onSuggestionClicked(String cardId) is called and activity's content is replaced with a new PagerFragment_new.
#Override
public void onSuggestionClicked(String cardId) {
Log.d("activity","ID:\t" + cardId);
PagerFragment_new pagerFragment = PagerFragment_new.getInstance(
Injection.provideMtgDatabase(getApplicationContext()),
activityPresenter.getAllCardExpansionIds(cardId),
this);
ActivityUtils.replaceFragment(getSupportFragmentManager(), pagerFragment, R.id.MTGRecallActivity_container);
}
PagerFragment_new contains a ViewPager to display CardInfoFragment_new
public class PagerFragment_new extends MtgRecallFragment_new implements PagerFragmentContract.View {
private View fragmentView;
private ViewPager viewPager;
private PagerFragmentContract.Presenter presenter;
private ScreenSlidePageAdapter_new adapter;
private MtgDatabase database;
private String[] printingsIds;
private ScreenSlidePageAdapter_new.ActivePresenterListener listener;
public PagerFragment_new() {
//Required empty constructor
}
public static PagerFragment_new getInstance(MtgDatabase database, String[] printingsIds, ScreenSlidePageAdapter_new.ActivePresenterListener listener) {
PagerFragment_new instance = new PagerFragment_new();
instance.setDatabase(database);
instance.setPrintingsIds(printingsIds);
instance.listener = listener;
return instance;
}
//other stuff
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
fragmentView = inflater.inflate(R.layout.fragment_pager, container, false);
viewPager = (ViewPager) fragmentView.findViewById(R.id.PAGERFRAG_VIEWPAGER);
adapter = new ScreenSlidePageAdapter_new(getChildFragmentManager(), printingsIds, database, viewPager);
adapter.setListener(listener);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
return fragmentView;
}
#Override
public void setPresenter(PagerFragmentContract.Presenter presenter) {
this.presenter = presenter;
}
}
The adapter to manage ViewPager's element's is ScreenSlidePageAdapter_new, it is responsible of instantiating CardInfoFragments.
public class ScreenSlidePageAdapter_new extends FragmentStatePagerAdapter {
private String[] printingsIds;
private String firstItemId;
private MtgDatabase database;
public ActivePresenterListener activity;
private ViewPager viewPager;
public ScreenSlidePageAdapter_new(FragmentManager fm, String[] printingsIds, MtgDatabase database, ViewPager viewPager) {
super(fm);
this.printingsIds =printingsIds;
this.database = database;
this.firstItemId = printingsIds[0];
this.viewPager = viewPager;
}
#Override
public Fragment getItem(int position) {
//todo create a bundle with cardId
Bundle bundle = new Bundle();
bundle.putString("CardID", printingsIds[position]);
bundle.putString("FirstItemId", firstItemId);
CardInfoFragment_new cardInfoFragment_new = CardInfoFragment_new.getInstance(viewPager);
cardInfoFragment_new.setArguments(bundle);
CardInfoPresenter cardInfoPresenter = new CardInfoPresenter(cardInfoFragment_new, database);
activity.setActivePresenter(cardInfoPresenter);
return cardInfoFragment_new;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
public void setListener(ActivePresenterListener listener) {
this.activity = listener;
}
#Override
public int getCount() {
return printingsIds.length;
}
public interface ActivePresenterListener {
void setActivePresenter(BasePresenter presenter);
}}
Finally, here's the code of CardInfoFragment:
public class CardInfoFragment_new extends MtgRecallFragment_new
implements CardInfoContract.View,
CardPrintingsAdapter.OnItemClickListener {
private ViewPager viewPager;
public CardInfoContract.Presenter presenter;
private View fragmentView;
private MTGCard mtgCard;
RecyclerView printingsRecyclerView;
CardPrintingsAdapter cardPrintingsAdapter;
private String firstItemId; //the first id
public CardInfoFragment_new() {
//required empty constructor
}
private void setViewPager(ViewPager viewPager) {
this.viewPager = viewPager;
}
public static CardInfoFragment_new getInstance(ViewPager viewPager) {
CardInfoFragment_new cardInfoFragment_new = new CardInfoFragment_new();
cardInfoFragment_new.setViewPager(viewPager);
return cardInfoFragment_new;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setRetainInstance(true);
presenter.start();
String cardId = getArguments().getString("CardID");
firstItemId = getArguments().getString("FirstItemId");
mtgCard = presenter.getCardData(cardId);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
fragmentView = inflater.inflate(R.layout.fragment_card_info_new, container, false);
setUpCardInfoView(fragmentView);
return fragmentView;
}
public void setUpCardInfoView(final View view){
//others view set-up action omitted
cardprintingsContainer = (LinearLayout) view.findViewById(R.id.CARDINFO_printingsContainer);
printingsRecyclerView = (RecyclerView)fragmentView.findViewById(R.id.CARDINFO_printings_recyclerView);
final List<String> printings = presenter.getCardPrintings(firstItemId, mtgCard.getName());
if (printings.size() < 40) {
setupPrintings(printings,printingsRecyclerView);
}
else {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout printingsRow = new LinearLayout(getContext());
printingsRow = (LinearLayout)inflater.inflate(R.layout.card_info_printings_row,printingsRow,true);
printingsRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setupPrintings(printings, printingsRecyclerView);
}
});
ImageView printingssetImage = (ImageView)printingsRow.findViewById(R.id.CARDINFO_printingsRow_setImage);
printingssetImage.setVisibility(View.INVISIBLE);
TextView printingssetName = (TextView)printingsRow.findViewById(R.id.CARDINFO_printingsRow_setName);
printingssetName.setText("Click to see all the "+printings.size()+ " versions");
cardprintingsContainer.addView(printingsRow);
}
}
public void setupPrintings(List<String> printings, RecyclerView recyclerView) {
cardPrintingsAdapter =
new CardPrintingsAdapter(getContext(), printings);
cardPrintingsAdapter.setOnItemClickListener(this);
UnscrollableLayoutManager layoutManager = new UnscrollableLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setAdapter(cardPrintingsAdapter);
recyclerView.setLayoutManager(layoutManager);
}
#Override
public void onItemClick(View itemView, int position) {
int i = viewPager.getAdapter().getCount();
viewPager.setCurrentItem(position);
}
#Override
public void onDestroy() {
presenter = null;
mtgCard = null;
super.onDestroy();
}}
When user click on a RecyclerView item, CardInfoFragment's method onItemClick(View itemView, int position) is called and the viewpager is set to current position. Everything as expected.
THE PROBLEM
When the orientation changes, fragments are able to retain their states, but viewPager.setCurrentItem(position) does nothing, and i'm not able to change displayed fragment.
I already checked:
ViewPager instance and adapters instances corresponds to those passed to Fragments
onItemClick is fired
this questions question1 question2
If i use
android:configChanges="orientation|screenSize"
in manifest it works even after config changes, but i don't want to use this option since is discouraged.
Thanks in advance!
By default, when certain key configuration changes happen on Android (a common example is an orientation change), Android fully restarts the running Activity to help it adjust to such changes.
When you define android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Please don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself. Yes, I know what I'm doing".
So use configChanges.
The use of this is discouraged, IF you don't know how to use it. But for a case like this, I would suggest you use it. IF not, still the activity will be recreated. which just takes time, resources, and I don't see why you would want that to happen.
I have a recyclerView populated in a Fragment and I want to Launch a new Fragment and pass data from the adapter ,I try to use Bundles but it always give a null value this my Adapter Class
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition());
}
}
and this is my new Fragment that I want to launch
public class FragmentB extends Fragment {
TextView textview;
TextView textView2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.tv_name);
textView2= (TextView) view.findViewById(R.id.tv_job);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments!=null){
String name= arguments.get("NAME").toString();
String job= arguments.get("JOB").toString();
textview.setText(name);
textView2.setText(job);}
}
}
this is how I connect Fragment and recyclerview Adapter
with interface
public interface FragmentCommunication {
void respond(int position);
}
and this the Fragment where the recyclerview is populated
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position) {
FragmentB fragmentB=new FragmentB();
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
and my mainActivity class is just add the RecyclerViewFragment
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerViewFragment fragment=new RecyclerViewFragment();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.dumper,fragment).commit();
}
}
so what is the right way to launch fragmentB and pass the data from recyclerview Adapter to fragmentB
thank you guys for the answer,I solved the problem using an interface with String values to connect the adapter with the fragment that contains the recyclerview and the other fragment here is what I did exactly :
this is the interface
public interface FragmentCommunication {
void respond(int position,String name,String job);
}
and this is the adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private LayoutInflater inflater;
private List<Information> mList;
private FragmentCommunication mCommunicator;
public RecyclerAdapter(Context context, List<Information> list,FragmentCommunication communication) {
inflater = LayoutInflater.from(context);
mList = list;
mCommunicator=communication;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_row, parent, false);
MyViewHolder holder = new MyViewHolder(view,mCommunicator);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Information current = mList.get(position);
holder.name.setText(current.name);
holder.job.setText(current.job);
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",current.name);
bundle.putString("JOB",current.job);
fragmentB.setArguments(bundle);
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView job;
FragmentCommunication mComminication;
public MyViewHolder(View itemView, FragmentCommunication Communicator) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.tv_name);
job = (TextView) itemView.findViewById(R.id.tv_gob);
mComminication=Communicator;
name.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mComminication.respond(getAdapterPosition(),mList.get(getAdapterPosition()).name,mList.get(getAdapterPosition()).job);
}
}
}
the fragment that contains the recyclerview
public class RecyclerViewFragment extends Fragment {
RecyclerView mRecyclerView;
RecyclerAdapter mRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.recycler_fragment,container,false);
mRecyclerView= (RecyclerView) view.findViewById(R.id.recycler);
mRecyclerAdapter=new RecyclerAdapter(getActivity(),getData(),communication);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public static List<Information> getData() {
List<Information>data=new ArrayList<>();
String[] names={"ahmed","mohammed"};
String[] jobs={"sacsd","csscs"};
for (int i=0;i<names.length;i++){
Information current=new Information();
current.name=(names[i]);
current.job=(jobs[i]);
data.add(current);
}
return data;
}
FragmentCommunication communication=new FragmentCommunication() {
#Override
public void respond(int position,String name,String job) {
FragmentB fragmentB=new FragmentB();
Bundle bundle=new Bundle();
bundle.putString("NAME",name);
bundle.putString("JOB",job);
fragmentB.setArguments(bundle);
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.replace(R.id.dumper,fragmentB).commit();
}
};
}
this is the fragmentB where I get the Strings from the Adapter
public class FragmentB extends Fragment {
TextView textview;
TextView textview2;
String name;
String job;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name=getArguments().getString("NAME");
job=getArguments().getString("JOB");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_b,container,false);
textview= (TextView) view.findViewById(R.id.getName);
textview2= (TextView) view.findViewById(R.id.getJob);
textview.setText(name);
textview2.setText(job);
return view;
}
}
If you are working with kotlin, the solution is much simpler.
Original Answer here
pass the function val itemClick: (Int) -> Unit to your adapter.
class MyRecyclerViewAdapter(params , val itemClick: (Int) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
itemView.setOnClickListener( {itemClick(layoutPosition)} )
}
}
In your fragment use the returned value position
val myAdapter = MyRecyclerViewAdapter(params) { position ->
// do something
}
Either creating a listener interface in the adapter or using regular old getters, if I understand your question correctly.
You need to pass the Bundle to the fragment through the setArguments(Bundle args) method. Since you have not set arguments, the bundle you try to extract in your Fragment resolves to null.
You have the right idea with using a Bundle. You just need to pass it to the Fragment by calling setArguments(). Then you retrieve the Bundle in your Fragment with getArguments().
Note that instead of mList.get(position).name, you can do current.name. Similarly for job.
Another part of the problem is that you create FragmentB on two different places. In one place you also call setArguments() but do not show the fragment. In the other you show the fragment but do not call setArguments(). If you really need to do this from multiple parts of your code you should write a method to avoid these inconsistencies.
I have a ViewPager with fragments in my activity, each page has a textview, I want to change the text of the textview from the onCreate method in the activity that contains the viewpager. How should I go about doing that?
below is the code that would return a null object exception:
Fragment:
public class MyFragment extends Fragment {
private TextView textView;
public static MyFragment getInstance(){
return new MyFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
return rootView;
}
public void setText(String text){
textView.setText(text);
}
}
Adapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return MyFragment.getInstance();
}
#Override
public int getCount() {
return 3;
}
}
Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
MyFragment fragment = (MyFragment) adapter.getItem(0);
fragment.setText("Altered"); // and this returns null pointer exception
}
Thank you!
Most FragmentPagerAdapters will have an addFragment method and will keep track various fragments that are added to it via an internal object:
public class MyPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
As it stands, your implementation of getItem returns a new instance of MyFragment every time it is called. As such, MyFragment fragment = (MyFragment) adapter.getItem(0); is a new instance that will never be loaded into the ViewPager, will never be inflated, and hence has a null textView reference.
The other issue is that within the onCreate of your activity, the fragments have not yet been inflated, so the textView will be null unless you delay the call:
final MyFragment fragment = (MyFragment) mPagerAdapter.getItem(0);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
fragment.setText("Altered");
}
}, 100);
But really, why not just set it to the correct value when it is initialized?
Try This
Fragment:
public class MyFragment extends Fragment {
private TextView textView;
private String Text;
public MyFragment (String Text){
this.Text=Text;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
textView.setText(Text);
return rootView;
}
}
Adapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new MyFragment("Altered");
}
#Override
public int getCount() {
return 3;
}
}
Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}