how to call the viewPager adapter from another fragmentClass - android

I need to implement a fragment replacement in the ViewPager.
After some search, I found this adapter (that seems to work good):
public class ViewPagerAdapter extends FragmentStatePagerAdapter implements ViewPager.OnPageChangeListener
{
private final AppCompatActivity mActivity;
private final TabLayout tabLayout;
private final ViewPager mPager;
private List<TabInfo> mTabs = new LinkedList<TabInfo>();
private int TOTAL_TABS;
private Map<Integer, Stack<TabInfo>> history = new HashMap<Integer, Stack<TabInfo>>();
public ViewPagerAdapter(AppCompatActivity activity, ViewPager pager, TabLayout tabLayout)
{
super(activity.getSupportFragmentManager());
activity.getSupportFragmentManager();
this.mActivity = activity;
this.mPager = pager;
this.tabLayout = tabLayout;
}
public void addTab(final Class fragmentClass, final Bundle args)
{
final TabInfo tabInfo = new TabInfo(fragmentClass, args);
tabLayout.newTab();
tabLayout.setTag(tabInfo);
mTabs.add(tabInfo);
notifyDataSetChanged();
}
#Override
public Fragment getItem(final int position)
{
final TabInfo tabInfo = mTabs.get(position);
return Fragment.instantiate(mActivity, tabInfo.fragmentClass.getName(), tabInfo.args);
}
#Override
public int getItemPosition(final Object object) {
int position = tabLayout.getSelectedTabPosition();
int pos = POSITION_NONE;
if (history.get(position).isEmpty()) {
return POSITION_NONE;
}
for (Stack<TabInfo> stack : history.values()) {
TabInfo c = stack.peek();
if (c.fragmentClass.getName().equals(object.getClass().getName())) {
pos = POSITION_UNCHANGED;
break;
}
}
return pos;
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position)
{
}
public void onTabSelected(final FragmentTransaction ft) {
TabInfo tabInfo = (TabInfo) tabLayout.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i).equals(tabInfo)) {
mPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(FragmentTransaction ft) {
}
public void onTabReselected(FragmentTransaction ft) {
}
public void replace(final int position, final Class fragmentClass, final Bundle args)
{
mActivity.getSupportFragmentManager().beginTransaction().addToBackStack(null).commit();
updateTabs(new TabInfo(fragmentClass, args), position);
history.get(position).push(new TabInfo(mTabs.get(position).fragmentClass, mTabs.get(position).args));
notifyDataSetChanged();
}
private void updateTabs(final TabInfo tabInfo, final int position)
{
mTabs.remove(position);
mTabs.add(position, tabInfo);
tabLayout.getTabAt(position).setTag(tabInfo);
}
public void createHistory()
{
int position = 0;
TOTAL_TABS = mTabs.size();
for (TabInfo mTab : mTabs)
{
if (history.get(position) == null)
{
history.put(position, new Stack<TabInfo>());
}
history.get(position).push(new TabInfo(mTab.fragmentClass, mTab.args));
position++;
}
}
public void back()
{
int position = tabLayout.getSelectedTabPosition();
if (!historyIsEmpty(position))
{
if (isLastItemInHistory(position))
{
mActivity.finish();
}
final TabInfo currentTabInfo = getPrevious(position);
mTabs.clear();
for (int i = 0; i < TOTAL_TABS; i++)
{
if (i == position)
{
mTabs.add(new TabInfo(currentTabInfo.fragmentClass, currentTabInfo.args));
}
else
{
TabInfo otherTabInfo = history.get(i).peek();
mTabs.add(new TabInfo(otherTabInfo.fragmentClass, otherTabInfo.args));
}
}
}
notifyDataSetChanged();
}
private boolean historyIsEmpty(final int position)
{
return history == null || history.isEmpty() || history.get(position).isEmpty();
}
private boolean isLastItemInHistory(final int position)
{
return history.get(position).size() == 1;
}
private TabInfo getPrevious(final int position)
{
TabInfo currentTabInfo = history.get(position).pop();
if (!history.get(position).isEmpty()) {
currentTabInfo = history.get(position).peek();
}
return currentTabInfo;
}
private static class TabInfo
{
public Class fragmentClass;
public Bundle args;
public TabInfo(Class fragmentClass, Bundle args)
{
this.fragmentClass = fragmentClass;
this.args = args;
}
public boolean equals(final Object o)
{
return this.fragmentClass.getName().equals(o.getClass().getName());
}
public int hashCode() {
return fragmentClass.getName() != null ? fragmentClass.getName().hashCode() : 0;
}
public String toString() {
return "TabInfo{" +
"fragmentClass=" + fragmentClass +
'}';
}
}
}
and I need to call methods replace() and back() in this adapter.
This is how I call this adapter from WindFragment in setupViewPager() method:
private void setupViewPager(ViewPager viewPager, TabLayout tabLayout)
{
adapter = new ViewPagerAdapter((AppCompatActivity)getActivity(),viewPager,tabLayout);
adapter.addTab(THGSFragment.class,null);
adapter.addTab(FlightPerformanceFragment.class,null);
adapter.addTab(AviationConverterFragment.class,null);
adapter.addTab(SpeedFragment.class,null);
adapter.createHistory();
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setText(getString(R.string.thgs));
tabLayout.getTabAt(1).setText(getString(R.string.tcgs));
tabLayout.getTabAt(2).setText(getString(R.string.wv));
tabLayout.getTabAt(3).setText(getString(R.string.thtas));
}
now I'm in this class:
public class THGSFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_thg, container, false);
ImageView button= (ImageView) rootView.findViewById(R.id.calcEAS);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
}
});
return rootView;
}
}
and in the onClick() method I need to call the method replace() from the adapter, but I don't know how.
So, I need to use an interface (that I'm not good to use) ?
Thank you

Related

How to send input from searchview which is in an activity to fragment which is in the view pager of that activity

So i have a searchview placed in an activity which has a tablayout and viewpager.In the viewpager there is a fragment for each tab with a textview.What im trying to do is to get the input from the searchview and set the text of the textview with that input and i cant seem to be able to do it.I tried to put the input from the searchview in a bundle(this being done in the activity),and then get the arguments in the fragment in onCreateView() but the problem is that the activity and the fragment are being created simultaneously wthich means that the input from the searchview would be null.
This is the Activity:
public class SearchActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
SearchView searchView;
Toolbar toolbar;
ImageButton imageButtonBack;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
bindUI();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.AddFragment(new NewestFragment(), "Newest"); // this line can cause crashes
viewPagerAdapter.AddFragment(new OldestFragment(), "Oldest"); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
setSearchView();
setImageButtonBack();
}
private void setSearchView() {
searchView.requestFocus();
View v = searchView.findViewById(R.id.search_plate);
v.setBackgroundColor(Color.parseColor("#ffffff"));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
searchView.clearFocus();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
return false;
}
});
}
private void bindUI() {
imageButtonBack = findViewById(R.id.back);
tabLayout = findViewById(R.id.tabs);
viewPager = findViewById(R.id.view_pager);
searchView = findViewById(R.id.search_view_searchactivity);
toolbar = findViewById(R.id.toolbar_selected_category);
}
private void setImageButtonBack() {
imageButtonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
The adapter of the ViewPager:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> titlesList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fragmentManager) {
super(fragmentManager);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return titlesList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titlesList.get(position);
}
public void AddFragment(Fragment fragment, String title) {
fragmentList.add(fragment); // this line can cause crashes
titlesList.add(title);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
And here is the fragment:
public class NewestFragment extends Fragment {
View view;
TextView textView;
public NewestFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_search_newest, container, false);
textView=view.findViewById(R.id.tttttttttttttttttttt);
try {
String searchViewText=getArguments().getString("searchViewText");
textView.setText(searchViewText);
}
catch (Exception e){
//something
}
return view;
}
}
The fragments are attached to activity so first activity is created lets leave that but I think you should use a MVVM pattern and create viewmodel and then you can observe the search view and update the fragment textview using that viewmodel class
https://codelabs.developers.google.com/codelabs/kotlin-android-training-live-data/index.html#0
To change the fragments that are created by a FragmentPagerAdapter, you should use a DynamicFragmentPagerAdapter. Refer to the following code below.
public class DynamicFragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "DynamicFragmentPagerAdapter";
private final FragmentManager fragmentManager;
public static abstract class FragmentIdentifier implements Parcelable {
private final String fragmentTag;
private final Bundle args;
public FragmentIdentifier(#NonNull String fragmentTag, #Nullable Bundle args) {
this.fragmentTag = fragmentTag;
this.args = args;
}
protected FragmentIdentifier(Parcel in) {
fragmentTag = in.readString();
args = in.readBundle(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fragmentTag);
dest.writeBundle(args);
}
protected final Fragment newFragment() {
Fragment fragment = createFragment();
Bundle oldArgs = fragment.getArguments();
Bundle newArgs = new Bundle();
if(oldArgs != null) {
newArgs.putAll(oldArgs);
}
if(args != null) {
newArgs.putAll(args);
}
fragment.setArguments(newArgs);
return fragment;
}
protected abstract Fragment createFragment();
}
private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();
private FragmentTransaction currentTransaction = null;
private Fragment currentPrimaryItem = null;
public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) {
for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) {
FragmentIdentifier identifier = fragmentIdentifiers.get(i);
if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) {
return i;
}
}
return -1;
}
public void addFragment(FragmentIdentifier fragmentIdentifier) {
if (findIndexIfAdded(fragmentIdentifier) < 0) {
fragmentIdentifiers.add(fragmentIdentifier);
notifyDataSetChanged();
}
}
public void removeFragment(FragmentIdentifier fragmentIdentifier) {
int index = findIndexIfAdded(fragmentIdentifier);
if (index >= 0) {
fragmentIdentifiers.remove(index);
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return fragmentIdentifiers.size();
}
#Override
public void startUpdate(#NonNull ViewGroup container) {
if (container.getId() == View.NO_ID) {
throw new IllegalStateException("ViewPager with adapter " + this
+ " requires a view id");
}
}
#SuppressWarnings("ReferenceEquality")
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
// Do we already have this fragment?
final String name = fragmentIdentifier.fragmentTag;
Fragment fragment = fragmentManager.findFragmentByTag(name);
if (fragment != null) {
currentTransaction.attach(fragment);
} else {
fragment = fragmentIdentifier.newFragment();
currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#SuppressWarnings("ReferenceEquality")
#Override
public void setPrimaryItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(#NonNull ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitNowAllowingStateLoss();
currentTransaction = null;
}
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
return bundle;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = ((Bundle)state);
bundle.setClassLoader(loader);
fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
}
}

how to get the text of text-view inside view-pager current page in Toast

I want to get the TextView text of current page of ViewPager in toast in onPageSelected() . Remember my data is in array-list , if I remove any position from array-list that text should not be shown in toast on swipe view-pager.
Below is my code:
public class MainActivity extends FragmentActivity {
public static TextView tx;
CustomViewPager pager1;
List<Fragment> fragments1;
public PagerAdapter adapter1;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
pager1 = (CustomViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new PagerAdapter(getSupportFragmentManager(), fragments1);
pager1.setAdapter(adapter1);
removeView1(1);
adapter1.notifyDataSetChanged();
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
String S= (String) tx.getTag();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +S, Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(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();
}
#Override
public int getItemPosition (Object object)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
return position;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < image.size(); i++) {
fList.add(MyImageSlider.newInstance(image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
String newid;
public static MyImageSlider newInstance(String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
tx = (TextView)view.findViewById(R.id.text);
tx.setText(newid);
tx.setTag(newid);
return view;
}
}
}
Please try this code
public class MainActivity extends FragmentActivity {
public static TextView tx;
CustomViewPager pager1;
List<Fragment> fragments1;
public PagerAdapter adapter1;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
pager1 = (CustomViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new PagerAdapter(getSupportFragmentManager(), fragments1);
pager1.setAdapter(adapter1);
removeView1(1);
adapter1.notifyDataSetChanged();
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
MyImageSlider fragmntDta = (MyImageSlider ) findFragmentByPosition(mCurrentPos);
String value = fragmntDta.getTextOnTextView();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +value, Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(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();
}
#Override
public int getItemPosition (Object object)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
return position;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < image.size(); i++) {
fList.add(MyImageSlider.newInstance(image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
String newid;
TextView textView;
public static MyImageSlider newInstance(String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextOnTextView(){
retrun textView.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
textView = (TextView)view.findViewById(R.id.text);
textView.setText(newid);
textView.setTag(newid);
return view;
}
}
public Fragment findFragmentByPosition(int position) {
MyImageSlider fragmentPagerAdapter = mAdapter;
return getSupportFragmentManager().findFragmentByTag("android:switcher:" + mHorizontalViewPager.getId() + ":" + fragmentPagerAdapter.getItemId(position));
}
}
you should follow AndiGeeky's solutions.
In addition to that solution, you can even get a view which is visible on that position.
View view = pager1.getChildAt(position);
and later on get that textview by using view.findViewById(R.id.textviewid)
your code should look something like this.
#Override
public void onPageSelected(int position) {
View view = pager1.getChildAt(position);
TextView tv = (TextView)view.findViewById(R.id.<textviewId>);
Toast toast = Toast.makeText(getApplicationContext(),"Text is " + tv.getText().toString(), Toast.LENGTH_SHORT);
toast.show();
}
Note : textviewId will be the id of your TextView which is in Fragment

Add fragment to TabLayout on runtime

I've got a TabLayout in my Activity, it shows one fragment when it's created, but I need to be able to add a new fragment to it after completing an operation (or create both when the activity is created, but show only the first, and then show the second).
I've tried adding the fragment to the viewPagerAdapter and then calling the notifyDataSetChanged() method, the frament it's added, but it's title doesn't show up in the tabLayout and if I try to slide to it, I get an IndexOutOfBoundsException: Invalid index 1, size is 1
Does anyone got some advice to give me?
My activity, where I add the first fragmen:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_one);
// Crete a new fragment
FragmentOne fragmentOne = new FragmentoOne();
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
// Creates the viewPagerAdapter
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
// Adds the fragment to ViewPagerAdapter
viewPagerAdapter.addFragment(fragmentoOne, "First"); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
And here is where I try to add the new fragment:
public void onAddFragment2() {
viewPagerAdapter.addFragment(new FragmentoTwo(), "Second"); // new FragmentoTwo() should be in FragmentPagerAdapter.getItem()
viewPagerAdapter.notifyDataSetChanged();
}
set the adapter again after you added it with setAdapter
This is important, if you have 3 fragment you shout write 3 in your Adapter.
#Override
public int getCount() {
return 3;
}
To modify the contents of a FragmentPagerAdapter, you need to use the following code:
public class DynamicFragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "DynamicFragmentPagerAdapter";
private final FragmentManager fragmentManager;
public static abstract class FragmentIdentifier implements Parcelable {
private final String fragmentTag;
private final Bundle args;
public FragmentIdentifier(#NonNull String fragmentTag, #Nullable Bundle args) {
this.fragmentTag = fragmentTag;
this.args = args;
}
protected FragmentIdentifier(Parcel in) {
fragmentTag = in.readString();
args = in.readBundle(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fragmentTag);
dest.writeBundle(args);
}
protected final Fragment newFragment() {
Fragment fragment = createFragment();
Bundle oldArgs = fragment.getArguments();
Bundle newArgs = new Bundle();
if(oldArgs != null) {
newArgs.putAll(oldArgs);
}
if(args != null) {
newArgs.putAll(args);
}
fragment.setArguments(newArgs);
return fragment;
}
protected abstract Fragment createFragment();
}
private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();
private FragmentTransaction currentTransaction = null;
private Fragment currentPrimaryItem = null;
public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) {
for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) {
FragmentIdentifier identifier = fragmentIdentifiers.get(i);
if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) {
return i;
}
}
return -1;
}
public void addFragment(FragmentIdentifier fragmentIdentifier) {
if (findIndexIfAdded(fragmentIdentifier) < 0) {
fragmentIdentifiers.add(fragmentIdentifier);
notifyDataSetChanged();
}
}
public void removeFragment(FragmentIdentifier fragmentIdentifier) {
int index = findIndexIfAdded(fragmentIdentifier);
if (index >= 0) {
fragmentIdentifiers.remove(index);
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return fragmentIdentifiers.size();
}
#Override
public void startUpdate(#NonNull ViewGroup container) {
if (container.getId() == View.NO_ID) {
throw new IllegalStateException("ViewPager with adapter " + this
+ " requires a view id");
}
}
#SuppressWarnings("ReferenceEquality")
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
// Do we already have this fragment?
final String name = fragmentIdentifier.fragmentTag;
Fragment fragment = fragmentManager.findFragmentByTag(name);
if (fragment != null) {
currentTransaction.attach(fragment);
} else {
fragment = fragmentIdentifier.newFragment();
currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#SuppressWarnings("ReferenceEquality")
#Override
public void setPrimaryItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(#NonNull ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitNowAllowingStateLoss();
currentTransaction = null;
}
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
return bundle;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = ((Bundle)state);
bundle.setClassLoader(loader);
fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
}
}
Then generally, to make a modification actually happen (because ViewPagers are quirky), you'll most likely need:
viewPager.setAdapter(null);
viewPager.setAdapter(adapter);

How to destroy a Fragment programmatically in FragmentStatePagerAdapter

I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}

How does findFragmentByTag work in a parent Fragment to know which child fragment is currently showing with ViewPagerAdapter?

My MainFragment is like
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(3);
// changeTab();
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
pager.setCurrentItem(position_tab);
}
Log.e("Fragment", fragment + "" +pager.getCurrentItem());
//
return view;
}
public void changeTab(){
pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss" ,(Fragment) maps.get(position).get(KEY_FRAGMENT) +"");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
#Override
public int getCount() {
return maps.size();
}
}
}
Here I can get that this fragment is visible by using findFragmentByTag. I wanna know how I can use same thing for the child of this Fragment which are added using FragmentPagerAdapter.
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
Log.e("Fragment", fragment + "" +pager.getCurrentItem()); }
So now I wanna do same thing and get name of current selected Fragment out of 3 which are mentioned above in FragmentPagerAdapter as AdvisoryPagerFragment,TopAdvisoryPagerFragment and ExperViewPagerFragment.
Try this
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if(fragment instanceOf Fragment1){
// Do something
}else if(fragment instanceOf Fragment2){
// Do something
}else{
// Do something
}

Categories

Resources