I have tried a lot to implement a CardView which inside has a ViewPager (with fragments) and a TabLayout but RecyclerView shows only the first item and not the others.
Here is my ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int tabCount;
public ViewPagerAdapter(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount= tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
default:
return null;
}
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return tabCount;
}
}
Here is my TimeSheetAdapter:
public class TimeSheetAdapter extends RecyclerView.Adapter<TimeSheetAdapter.ViewHolder> {
Context context;
ArrayList<TimeSheet> timeSheetArrayList;
public TimeSheetAdapter(Context context, ArrayList<TimeSheet> timeSheetArrayList) {
this.context = context;
this.timeSheetArrayList = timeSheetArrayList;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
public ViewHolder(View itemView) {
super(itemView);
tabLayout = (TabLayout) itemView.findViewById(R.id.tabLayout);
viewPager = (ViewPager) itemView.findViewById(R.id.pager);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOffscreenPageLimit(2);
tabLayout.setupWithViewPager(viewPager);
}
}
public TimeSheetAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View viewHolder = LayoutInflater.from(parent.getContext()).inflate(R.layout.time_sheet_row, parent, false);
return new TimeSheetAdapter.ViewHolder(viewHolder);
}
#Override
public void onBindViewHolder(TimeSheetAdapter.ViewHolder holder, int position) {
ViewPagerAdapter adapter = new ViewPagerAdapter(((AppCompatActivity) context).getSupportFragmentManager(), holder.tabLayout.getTabCount());
holder. viewPager.setAdapter(adapter);
if (holder.tabLayout != null) {
for (int i = 0; i < holder.tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = holder.tabLayout.getTabAt(i);
if (tab != null)
tab.setText("Tab " + Integer.toString(i + 1));
}
}
holder.viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(holder.tabLayout));
}
#Override
public int getItemCount() {
return timeSheetArrayList.size();
}
}
The key is to assign unique ids to each ViewPager using setId() method, even they are inside rows of the RecyclerView.
Update ViewPagerAdapter as follows:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private String[] tabTitles = new String[] {"Tab 1", "Tab 2"};
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
Update TimeSheetAdapter as follows:
public class TimeSheetAdapter extends RecyclerView.Adapter<TimeSheetAdapter.ViewHolder> {
private Context context;
private ArrayList<TimeSheet> timeSheetArrayList;
public TimeSheetAdapter(Context context, ArrayList<TimeSheet> timeSheetArrayList) {
this.context = context;
this.timeSheetArrayList = timeSheetArrayList;
}
public TimeSheetAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View viewHolder = LayoutInflater.from(parent.getContext()).inflate(R.layout.time_sheet_row, parent, false);
return new TimeSheetAdapter.ViewHolder(viewHolder);
}
#Override
public void onBindViewHolder(TimeSheetAdapter.ViewHolder holder, int position) {
ViewPagerAdapter adapter = new ViewPagerAdapter(((AppCompatActivity) context).getSupportFragmentManager());
holder.viewPager.setAdapter(adapter);
holder.tabLayout.setupWithViewPager(holder.viewPager);
holder.viewPager.setOffscreenPageLimit(2);
}
#Override
public int getItemCount() {
return timeSheetArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TabLayout tabLayout;
ViewPager viewPager;
public ViewHolder(View itemView) {
super(itemView);
tabLayout = itemView.findViewById(R.id.tabLayout);
viewPager = itemView.findViewById(R.id.pager);
// Assign a unique id so that ViewPager is shown.
// Following method is an example and can be unreliable.
viewPager.setId((int) (Math.random() * 10000));
}
}
}
And MainActivity should be as follows:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<TimeSheet> timeSheetArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
TimeSheetAdapter adapter = new TimeSheetAdapter(this, timeSheetArrayList);
recyclerView.setAdapter(adapter);
fetchData(); // Populate timeSheetArrayList
}
...
}
Related
In my viewpager i set listener from which i call methods from my interface in tab fragments.
But variable in this tab fragments in my interfaces methods always return null.
Tell me why ?
p.s. sorry for my english)
Parent fragment:
public class MyFragment
extends Fragment {
protected Context mContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public void onDetach() {
super.onDetach();
mContext = null;
} }
Container fragment with PagerAdapter:
public class FragmentContainer
extends MyFragment {
private ViewPager viewPager;
private ViewPager.OnPageChangeListener onPageChangeListener;
public interface IPageSelected {
void onPageSelected();
void onPageUnselected();
}
public static FragmentContainer newInstance() {
return new FragmentContainer();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.fragment_container, container, false);
viewPager = view.findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int x = 0; x < pagerAdapter.getCount(); x++) {
((IPageSelected) pagerAdapter.getItem(x)).onPageUnselected();
}
((IPageSelected) pagerAdapter.getItem(position)).onPageSelected();
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
viewPager.addOnPageChangeListener(onPageChangeListener);
return view;
}
#Override
public void onResume() {
super.onResume();
setCurrentItem();
}
private void setCurrentItem() {
viewPager.post(() -> {
viewPager.setCurrentItem(0);
onPageChangeListener.onPageSelected(0);
});
}
class PagerAdapter
extends FragmentStatePagerAdapter {
PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TestFragment1.newInstance();
case 1:
return TestFragment2.newInstance();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab1";
case 1:
return "Tab2";
default:
return null;
}
}
} }
Tab fragments.
Question: why variable mContext in interface methods always return null ?
public class TestFragment1
extends MyFragment
implements FragmentContainer.IPageSelected {
public static TestFragment1 newInstance() {
return new TestFragment1();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
#Override
public void onPageSelected() {
Log.d("myLog", "TestFragment1 onPageSelected: " + mContext); // WHY NULL ???
}
#Override
public void onPageUnselected() {
Log.d("myLog", "TestFragment1 onPageUnselected: " + mContext); // WHY NULL ???
} }
public class TestFragment2
extends MyFragment
implements FragmentContainer.IPageSelected {
public static TestFragment2 newInstance() {
return new TestFragment2();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
#Override
public void onPageSelected() {
Log.d("myLog", "TestFragment2 onPageSelected: " + mContext); // WHY NULL ???
}
#Override
public void onPageUnselected() {
Log.d("myLog", "TestFragment2 onPageUnselected: " + mContext); // WHY NULL ???
} }
In your fragment container :
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager()); here is the fault.
In order to attach your child fragments to your container fragment, consider passing child fragment manager getChildFragmentManager() to your viewpager adapter. (Right now your fragments are attached to same level as your container fragment).
I found solution.
Adapter class.
Old:
class PagerAdapter
extends FragmentStatePagerAdapter {
PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TestFragment1.newInstance();
case 1:
return TestFragment2.newInstance();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab1";
case 1:
return "Tab2";
default:
return null;
}
}
}
New:
class PagerAdapter
extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Adapter initialization.
Old:
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager());
viewPager.setAdapter(pagerAdapter);
New:
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager());
pagerAdapter.addFragment(TestFragment1.newInstance(), "tab1");
pagerAdapter.addFragment(TestFragment2.newInstance(), "tab2");
viewPager.setAdapter(pagerAdapter);
And now new question: what's the differense with the first option ?
Now i initializing adapter in container fragment, it's a cause ?
Why didn't work when initializing was in the adapter ?
I want to delete a fragment and it's view from a tablayout when a checkbox is checked from a recyclerview. I have skipped the initializing codes and will share only the adapter codes (as that's where the work is) like below:
ViewpagerAdapter code:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String TAG = ViewPagerAdapter.class.getSimpleName();
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> titlesList = new ArrayList<>();
private Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public ViewPagerAdapter(FragmentManager fm, Context ctx, ViewPager viewPager, TabLayout tabLayout) {
super(fm);
this.context = ctx;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragTab(Fragment fragment, String name){
fragmentList.add(fragment);
titlesList.add(name);
}
public void addFragLastPosition(Fragment fragment, String name){
fragmentList.add(fragmentList.size(), fragment);
titlesList.add(name);
}
public void removeFrag(int position){
removeTab(position);
Fragment fragment = fragmentList.get(position);
fragmentList.remove(fragment);
titlesList.remove(position);
destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
}
private void destroyFragmentView(ViewGroup container, int position, Object obj) {
FragmentManager manager = ((Fragment) obj).getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove((Fragment) obj).commit();
}
private void removeTab(int position) {
if (tabLayout.getChildCount() > 2){
tabLayout.removeTabAt(position);
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titlesList.get(position);
}
}
and recyclerview adapter with checkbox to delete and add fragment:
public class PrefsAdapter extends RecyclerView.Adapter<PrefsCustomizeViewHolder> {
private static final String TAG = PrefsAdapter.class.getSimpleName();
private final Context context;
private List<Customize> itemsList;
private long id_nature, id_space;
private Customize cust;
private String nature, space;
private ViewPagerAdapter pagerAdapter;
public PrefsAdapter(Context context, List<Customize> itemsList) {
this.context = context;
this.itemsList = itemsList;
pagerAdapter = new ViewPagerAdapter(((AppCompatActivity)context).getSupportFragmentManager());
}
#Override
public PrefsCustomizeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prefs_customize_items_layout, parent, false);
return new PrefsCustomizeViewHolder(view);
}
#Override
public void onBindViewHolder(final PrefsCustomizeViewHolder viewholder, final int position) {
final Customize customize = itemsList.get(position);
Picasso.with(context)
.load(customize.getIcon())
.fit()
.into(viewholder.prefsSelImg);
switch (position) {
case 0:
cust = new Select()
.from(Customize.class)
.where("tabName = ? ", Constants.NATURE)
.executeSingle();
if (cust != null) {
nature = cust.tabName;
Log.d(TAG, "Nature Tab From DB:\t" + nature);
id_nature = cust.getId();
Log.d(TAG, "Nature Tab Id from DB:\t" + id_nature);
viewholder.prefsCheckBox.setChecked(true);
} else {
viewholder.prefsCheckBox.setVisibility(View.INVISIBLE);
viewholder.prefsCheckBox.setChecked(false);
}
break;
case 1:
cust = new Select()
.from(Customize.class)
.where("tabName = ? ", Constants.SPACE)
.executeSingle();
if (cust != null) {
space = cust.tabName;
Log.d(TAG, "Space Tab From DB:\t" + space);
id_space = cust.getId();
Log.d(TAG, "Space Tab Id from DB:\t" + id_space);
viewholder.prefsCheckBox.setChecked(true);
} else {
viewholder.prefsCheckBox.setVisibility(View.INVISIBLE);
viewholder.prefsCheckBox.setChecked(false);
}
break;
}
viewholder.prefsSelImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (position) {
case 0:
if (viewholder.prefsCheckBox.isChecked()){
viewholder.prefsCheckBox.setChecked(false);
//Customize.delete(Customize.class, id_nature);
pagerAdapter.removeFrag(1); // not working
} else {
viewholder.prefsCheckBox.setChecked(true);
customize.setTabId(UUID.randomUUID().toString());
customize.setTabName(Constants.NATURE);
customize.save();
pagerAdapter.addFragTab(new NatureFrag(), Constants.NATURE); // not working too
viewholder.prefsCheckBox.setVisibility(View.VISIBLE);
}
break;
case 1:
if (viewholder.prefsCheckBox.isChecked()){
viewholder.prefsCheckBox.setChecked(false);
Customize.delete(Customize.class, id_space);
Log.d(TAG, "Deleted Space id:\t" + id_space); // prints right log detail
pagerAdapter.removeTab(new SpaceFragment(), Constants.SPACE);
} else {
viewholder.prefsCheckBox.setChecked(true);
customize.setTabId(UUID.randomUUID().toString());
customize.setTabName(Constants.NATURE);
customize.save();
pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);
viewholder.prefsCheckBox.setVisibility(View.VISIBLE);
}
break;
}
}
});
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
}
The method to delete the tab doesn't work. Can anyone help out with this implementation or another way? Thanks.
I want to add ViewPager with tablayout in my RecyclerView row. But fragment I add in ViewPager just show in firts row, from second row, just TabLayout show, fragment in ViewPager not show. I read and found that I need set ID for each ViewPager. ViewPager does not allow sharing of the id in the same fragment, even if it is part of a recyclerview context. But I don'nt know how to do that. Anyone can show me what exactly step I need to do or another method ? Thanks you very much.
Code my RecyclerView Adapter
public class ListArtifactsAdapter extends
RecyclerView.Adapter<ListArtifactsAdapter.ListArtifactsViewHolder>
{
private List<Artifact> artifacts;
private Context context;
public static class ListArtifactsViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ImageView mImageView;
public ViewPager mViewPager;
public TabLayout mTabLayout;
public ListArtifactsViewHolder(View itemView) {
super(itemView);
mTextView = (TextView)itemView.findViewById(R.id.titleTextView);
mImageView = (ImageView)itemView.findViewById(R.id.imageView);
View v = itemView.findViewById(R.id.function_tab);
mViewPager = (ViewPager)v.findViewById(R.id.pager);
mTabLayout = (TabLayout)v.findViewById(R.id.tab_layout);
}
}
public ListArtifactsAdapter(List<Artifact> artifacts, Context context){
this.artifacts = artifacts;
this.context = context;
}
#Override
public ListArtifactsAdapter.ListArtifactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ListArtifactsViewHolder vh = new ListArtifactsViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_demo, parent, false));
return vh;
}
#Override
public void onBindViewHolder(ListArtifactsAdapter.ListArtifactsViewHolder holder, int position) {
Artifact artifact = artifacts.get(position);
holder.mTextView.setText(artifact.getName());
holder.mImageView.setImageResource(R.drawable.add);
holder.mViewPager.setAdapter(new ArtifactInformationAdapter(((AppCompatActivity)context).getSupportFragmentManager(), artifact.getAudio(), artifact.getTranscript()));
holder.mTabLayout.setupWithViewPager(holder.mViewPager);
}
#Override
public int getItemCount() {
return artifacts.size();
}
}
My ViewPager Adapter
public class ArtifactInformationAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();
public ArtifactInformationAdapter(FragmentManager fragmentManager,String audio, String transcript) {
super(fragmentManager);
mFragmentList.add(AudioFragment.newInstance(audio));
mFragmentList.add(TranscriptFragment.newInstance(transcript));
mFragmentTitleList.add("Audio");
mFragmentTitleList.add("Transcript");
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I have implemented a ViewPager in order to swipe between two Fragments like such:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.statistics_general_vp, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mStatisticsPagerAdapter = new StatisticsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mStatisticsPagerAdapter);
return view;
}
public class StatisticsPagerAdapter extends FragmentStatePagerAdapter {
public StatisticsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new GeneralStatistics();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
But for now my two slides display the same Fragment.
How may I have slide 1 display Fragment 1 and slide 2 Fragment 2?
have u created fragment1 and fragment 2 seperately?? if yes then do this - in activity holding these two fragments.
private void createViewPager(ViewPager viewPager) {
Log.d("activity", "viewpager");
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment1(), "");
adapter.addFrag(new Fragment2(), "");
viewPager.setAdapter(adapter);
}
create fragment like this -
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.transaction_layout, container, false);
return v;
}
}
create viewpager like this -
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
or if you want to make tab with icons use this method -
private void createTabIcons() {
Log.d("activity", "createtabicons");
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabOne.setText("QR Scan");
tabOne.setTypeface(MRR);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image1, 0, 0);
tabOne.setCompoundDrawablePadding(5);
tabLayout.getTabAt(0).setCustomView(tabOne);
tabLayout.getTabAt(0).getCustomView().setSelected(true);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabTwo.setText("Mobile No.");
tabTwo.setTypeface(MRR);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image3, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
tabTwo.setCompoundDrawablePadding(5);
}
Hello i show you what i doing, i got 2 fragments in mainActivity
private void addFragments() {
List<Fragment> fragments = new ArrayList<>();
chatFragment = new ChatFragment();
remoteFragment = new RemoteFragment();
fragments.add(remoteFragment);
fragments.add(chatFragment);
MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(TAB_REMOTE_POSITION)
.setIcon(getDrawable(R.drawable.ic_settings_remote_white_24dp));
tabLayout.getTabAt(TAB_SOCIAL_POSITION)
.setIcon(getDrawable(R.drawable.ic_group_white_24dp));
}
Here is my adapter:
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
and on OnCreate u should
addFragments();
also i bind the views with ButterKnife
#Bind(R.id.view_pager)
ViewPager viewPager;
#Bind(R.id.tab_layout)
TabLayout tabLayout;
but u can static implement this with android
And remember that u have listeners:
private void pageChangeListener() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}
i use this tutorial for creating tab.
and now i have a recyclerview in each fragment and i want to notify them from mainactivity. how to access the adapter in fragment?
i use this for calling refreshData() method in fragment:
TabFragment1 tabFragment = (TabFragment1) getSupportFragmentManager().findFragmentByTag(TabFragment1.class.getSimpleName());
if (tabFragment != null) {
tabFragment.refreshData();
}
but that return null.
mainActivity:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
case 3:
TabFragment4 tab4 = new TabFragment4();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
One of myTabFragment:
public CardAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RecyclerView v = (RecyclerView) inflater.inflate(R.layout.tab_fragment_1, container, false);
SetupRecycleView(v);
return v;
}
public void refreshData() {
adapter.notifyDataSetChanged();
}
void SetupRecycleView(RecyclerView recList) {
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(G.context);
llm.setOrientation(LinearLayoutManager.VERTICAL);
//recList.setLayoutManager(new GridLayoutManager(G.context, 2));
recList.setLayoutManager(llm);
List<StructGhaza> ghazas = StructGhaza.getAllGhaza("2");
adapter = new CardAdapter(ghazas);
recList.setAdapter(adapter);
}
The CardAdapter:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.GhazaViewHolder> {
private List<StructGhaza> ghazas;
public CardAdapter(List<StructGhaza> ghazaList) {
this.ghazas = ghazaList;
}
#Override
public int getItemCount() {
return ghazas.size();
}
#Override
public void onBindViewHolder(GhazaViewHolder ghazaViewHolder, int position) {
StructGhaza ghaza = ghazas.get(position);
ghazaViewHolder.vTitle.setText(ghaza.Name);
//----Load Image
Glide.with(G.context)
.load(ghaza.Aks)
.placeholder(R.drawable.loading_spinner)
.crossFade()
.into(ghazaViewHolder.itemImg);
//---------------
ghazaViewHolder.Rate.setRating(ghaza.Star);
ghazaViewHolder.sampleLayout.setHoverView(ghazaViewHolder.hover);
ghazaViewHolder.sampleLayout.addChildAppearAnimator(ghazaViewHolder.hover, R.id.tvHover, Techniques.FlipInX);
ghazaViewHolder.sampleLayout.addChildDisappearAnimator(ghazaViewHolder.hover, R.id.tvHover, Techniques.FlipOutX);
}
#Override
public GhazaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.fragment_carditem, viewGroup, false);
return new GhazaViewHolder(itemView);
}
public static class GhazaViewHolder extends RecyclerView.ViewHolder {
protected TextView vTitle;
protected BlurLayout sampleLayout;
protected View hover;
protected ImageView itemImg;
protected RatingBar Rate;
public GhazaViewHolder(View v) {
super(v);
sampleLayout = (BlurLayout) v.findViewById(R.id.sample);
itemImg = (ImageView) v.findViewById(R.id.item_img);
hover = LayoutInflater.from(G.context).inflate(R.layout.fragment_hover, null);
vTitle = (TextView) v.findViewById(R.id.titleTv);
Rate = (RatingBar) v.findViewById(R.id.rating);
}
}
}
EDIT:
After many test, the previous answer work with Android < 21, but for Android > 21 it's little bit weird, it doesn't seems to work in the same way.
Finally, I solved it like that, and it works everywhere:
In your adapter:
HashMap<Integer, Fragment> mPageReferenceMap = new HashMap<>();
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
mPageReferenceMap.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mPageReferenceMap.remove(position);
}
public Fragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
And you call getFragment where you want in your activity like that:
int index = viewPager.getCurrentItem();
ViewPagerAdapter adapter = ((ViewPagerAdapter)viewPager.getAdapter());
final YourFragment tabFragment = (YourFragment) adapter.getFragment(index);
PREVIOUS ANSWER :
Warning : it doesn't really work with Android > 21
I had the same problem. Finally, i did'nt use id or tag.
Instead of using:
CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_custo_tag));
use this:
CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().getFragments().get(0);
to get instance of CustomFragment.
I have put get(0) as your position of CustomFragment instance is at zero.
I found this issue here:
Set and get using tag a fragment in android
This is late but I hope this will be helpful for someone. To find fragment by tag we can do this:
String tag=getSupportFragmentManager().getFragments().get(index).getTag();
SecondFragment f = (SecondFragment) getSupportFragmentManager().findFragmentByTag(tag);