FragmentPagerAdapter returns semi broke views on Reselect - java

I have a Tab Activity that has x amount of tabs. All the tabs load properly on the first load. If I go x+2 tabs away from a tab and then go back, some of the data and elements are missing.
I used the Android Studio's own Tabbed Activity generated template, as well as the Fragment templates for the tabs.
I have reviewed SO and a few others, but they do not seem to fit my model exactly. Or if they do, Im not seeing it.
Any help?
Here is my Master Tabbed Activity with some of the relevant imports.
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
public class MasterTabActivity extends AppCompatActivity {
public static Intent newIntent(Context packageContext) {
Intent intent = new Intent(packageContext, MasterTabActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
return intent;
}
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_master_tab);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
//get some data
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// Titles
tabLayout.addTab(tabLayout.newTab().setText("Details"));
tabLayout.addTab(tabLayout.newTab().setText("Photos"));
tabLayout.addTab(tabLayout.newTab().setText("Notes"));
//Add ICONS TO TEXT
tabLayout.getTabAt(0).setIcon(R.drawable.ic_details);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_photos);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_notes);
tabLayout.setTabTextColors(
ContextCompat.getColor(this, R.color.colorPrimary), //unselected
ContextCompat.getColor(this, R.color.colorDarkText) //selected
);
//Set the initial selected icons tab color
tabLayout.getTabAt(0).getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorDarkText), PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(1).getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(2).getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
// tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
tab.getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorDarkText), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
refreshData();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return DetailsFragment.newInstance(createdCallKey);
case 1:
return PhotosFragment.newInstance(createdCallKey);
case 2:
return NotesFragment.newInstance(createdCallKey);
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
}
}
And a sample of the fragments. At this point they are pretty much setup the same, save some basic GUI elements.
import android.support.v4.app.Fragment;
public class DetailsFragment extends Fragment {
public DetailsFragment() {
// Required empty public constructor
}
public static DetailsFragment newInstance(String callKey) {
DetailsFragment fragment = new DetailsFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
//do all the view setup
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}

In my Fragments I query the Tabbed Activity for some data. When a fragment moves more than x+2 tabs away, the Fragments onPausemethod (along with the other teardown methods) is called. Check the lifecycle documents for all the stages of the fragment.
When you return to the tab, the onCreateView method (along with the other build methods baring 1onAttach1 and onCreate. In my example above, the fragment queries the Activity in onCreate.
So I created a refreshData method:
private void refreshData() {
someTextElement.setText(((MasterTabActivity) getActivity()).getCallDetailsDictionary().getString("CALdCallTaken").getString("SomeKey"));
}
And moved the call to refreshData into onStart, first checking that the data in the activity is not null.
#Override
public void onStart() {
super.onStart();
Log.w(TAG, "-------------- onStart");
if (((MasterTabActivity) getActivity()).getCallDetailsDictionary() != null) {
refreshData();
}
}
Now, whenever that view returns into view, it will call onStart and refresh its data.

Related

Saving State In Fragment With ViewPager Android Studio

Need a little help on how to approach saving state in my single activity application. I looked at a few resources but couldn't quite find one that fits the build. Essentially I have single activity with a Fragment container view that I'm using to swap out fragments as needed. My issue is that as my activity is destroyed when a lifecycle event occurs, the fragment with my view pager is restored but the individual fragments on the tabs are not loaded. I cannot figure out how to save the state properly. Below is my code:
Activity:
public class StartActivity extends AppCompatActivity {
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mAuth = FirebaseAuth.getInstance();
if (savedInstanceState == null) {
LoginFragment fragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, fragment)
.commit();
}
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
MainActivity mainActivityFrag = new MainActivity();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, mainActivityFrag)
.commit();
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Fragment With View Pager:
public class MainActivity extends Fragment {
private FirebaseAuth mAuth;
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabs;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = mAuth = FirebaseAuth.getInstance();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
sectionsPagerAdapter = new SectionsPagerAdapter(getContext(),((AppCompatActivity)getActivity()).getSupportFragmentManager());
viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.showContextMenu();
toolbar = view.findViewById(R.id.topAppBar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
tabs.getTabAt(0).setIcon(R.drawable.home_selector);
tabs.getTabAt(1).setIcon(R.drawable.destination);
tabs.getTabAt(2).setIcon(R.drawable.mail_outline_blk);
tabs.getTabAt(3).setIcon(R.drawable.notification_bell);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.logout:
mAuth.signOut();
//navigate to home fragment
LoginFragment fragment = new LoginFragment();
((AppCompatActivity)getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment)
.commit();
return true;
default:
return false;
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Adapter Code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
PostFragment postFragment = new PostFragment();
return postFragment;
case 1:
TestFragment userFeedFragmentt = new TestFragment();
return userFeedFragmentt;
default:
TestFragment userFeedFragmenttt = new TestFragment();
return userFeedFragmenttt;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 2 total pages.
return 4;
}
}

Interaction between fragments in Tabbed activity

I am trying a simple interaction between two fragments in Tabbed activity.
I have a two layouts with TextView, EditText and Button. I am trying to achieve move text from EditText in FragmentOne to the EdidText (or TextView) in Fragment two when the Button from FragmentOne is pressed. But it doesnt works.
During debuging there isnt any problem. App doesnt stop working.
Is something problem in ViewPager or SectionsPagerAdapter?
I have this two fragments.
Fragments One:
public class FragmentOne extends Fragment {
TextView textView;
EditText editText;
Button button;
private OnFragmentOneInteractionListener mListener;
public FragmentOne()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
editText = (EditText) view.findViewById(R.id.fragOne_txb);
textView = (TextView) view.findViewById(R.id.fragTwo_header);
button = (Button) view.findViewById(R.id.fragOne_btn_to2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String text = editText.getText().toString();
mListener.onFragmentOneInteraction(text);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentOneInteractionListener
{
void onFragmentOneInteraction(String string);
}
}
And fragments two:
public class FragmentTwo extends Fragment{
private OnFragmentTwoInteractionListener mListener;
public EditText editText;
public FragmentTwo()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_two, container, false);
editText = (EditText) view.findViewById(R.id.fragTwo_txb);
return view;
}
public void onUpdateEditText(String string)
{
this.editText.setText(string);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentTwoInteractionListener) {
mListener = (OnFragmentTwoInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentTwoInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentTwoInteractionListener
{
void onFragmentTwoInteraction(Uri uri);
}
}
And this is my main activity:
public class MainActivity extends AppCompatActivity
implements FragmentOne.OnFragmentOneInteractionListener,
FragmentTwo.OnFragmentTwoInteractionListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
FragmentTwo fragmentTwo = new FragmentTwo();
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
}
I just tried your code and this is the update i did to make it work. Please mark it correct if its what you are looking for
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
fragmentTwo.onUpdateEditText(string);
/*FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);*/
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
FragmentTwo fragmentTwo = new FragmentTwo();
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
I suggest to use getActivity() instead
if (getActivity() instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) getActivity();
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}

How to start new Activity or refresh current Activity using viewpager

I have viewpager which is in fragment. I am looking to start a new activity or refresh the current activity using tabs on it
For now , I'm using this to open Fragment called "Sunday" and "Monday" But I would Like to add another tab and when user select this tab either refresh the current activity as same state when app is first opened or open new activity
Here is my code
public class MainActivity extends AppCompatActivity {
//RSS link
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new sectionB(), "SEC B");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == 0) {
Intent i1 = new Intent(MainActivity.this, SagarActivity.class);
startActivity(i1);
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For Refresh
If you want to refresh whole activity you can call recreate() method of activity
in your case you are in a fragment so you need to get activity first so you can do like getActivity().recreate()
For start new activity
for open a new activity you can use startActivity()
i your case you can do Like this
Intent intent = new Intent(getActivity(),activity_you_want_to_start.class);
startActivity(intent);
Remember one more thing, always make user getActivity() not returning
null
Now in your case
you need to setup listener on your TabLayout like this then call above method
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
//setting listener on tabLAyout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == yourDesiredPositionNumber) {
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
One Another Way is
You can also set Listener on ViewPager like this
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if(position==yourDesiredPositionNumber){
//here you can do your refresh of start new activity
}
super.onPageSelected(position);
}
});

How to make FloatingActionButton take you to specific tab in Tab Layout

I have a FloatingActionButton in my android navigation drawer with tablayout which displays the following message :
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeFragment();
SnackBarMessage("Go To Inbox.");
}
});
using snackbar
public void SnackBarMessage(String message){
Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
let's say I have 3 tabs e.g (tab 0 ,tab 1 , tab 2)
how can I make the Floating action button take me to tab 2 once I click on it
This is the fragment containing the tabs
public class HomeFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private OnFragmentInteractionListener mListener;
private SectionsPagerAdapter mSectionsPagerAdapter;
ArrayList<String> tabName;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
tabName=new ArrayList<String>();
int [] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_move_to_inbox,
R.drawable.ic_notifications,
R.drawable.ic_swap_horiz,
R.drawable.ic_people,
};
String[] strings = { "Main Page Goes Here", "Messages Go Here", "Notifications Go Here", "Trade Page Goes Here", "People Online Page Goes Here"};
for(int i=0;i<5;i++){
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[i]));
tabName.add((strings[i]));
}
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
getChildFragmentManager().beginTransaction().addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Note that we are passing childFragmentManager, not FragmentManager
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onResume() {
super.onResume();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
To be able to do this from another Fragment you will need to send a something in a Bundle, such as the position of the page, then do something like this:
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(YOUR_PAGE, youPage);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack("Name").commit();
Then in your HomeFragment:
Bundle bundle = this.getArguments();
if (bundle != null) { viewPager.setCurrentItem(bundle.getInt(YOUR_PAGE) }

How can I display Interstitial ad by pressing on the second tab in my navigationbar?

in my app I have a navigationbar with three tabs, each tab is a Fragment and the bar looks like this: https://gyazo.com/5052f885effb3e0154d407b3bd8d3884 It's simply a normal navigation bar with three tabs.
So now I want to display my Interstitial ad (which I load in my MainActivity onCreate) by pressing the second tab in this case the tab which is named "Ausraster".
So I did the following: I loaded the Interstitial ad in my MainActivity onCreate like this:
public class MainActivity extends AppCompatActivity{
public InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId("MY ID");
mInterstitialAd.loadAd(adRequest);
}
and then I wrote the displayInterstitial method in my MainActivity:
public void displayInterstitial() {
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
At last I wrote this line in the onCreateView of my second fragment the "Ausraster" fragment:
((MainActivity)getActivity()).displayInterstitial();
Should now actually fold everything but the problem is following: If I start the application the Interstitial Ad displays after a delay of 3 seconds without pressing on the second tab. But I want that its only display if I click on the second tab. So what can I do?
I have this problem now over a month and I would be so glad if someone can tell me why the Interstitial ad displays without pressing the second tab.
Here are all my codes, I hope you can explain it to me and sorry for my bad English :)
MainActivity:
public class MainActivity extends AppCompatActivity{
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
public InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the NavigationView
*/
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
/**
* Lets inflate the very first fragment
* Here , we are inflating the TabFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId("MyId");
mInterstitialAd.loadAd(adRequest);
}
public void displayInterstitial() {
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
}
}
TabFragment:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
if(position == 0){
return new KommentareFragment();
}
if(position == 1){
return new AusrasterFragment();
}
if(position == 2){
return new LustigesFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Kommentare";
case 1 :
return "Ausraster";
case 2 :
return "Lustiges";
}
return null;
}
}
final public void showInterstitial(){
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
if(mInterstitialAd.isLoaded()){
mInterstitialAd.show();
}
}
#Override
public void onAdClosed() {
}
});
}
}
And at last my secondFragment:
public class AusrasterFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.ausraster_layout,container,false);
return rootView;
}
The ViewPager loads other off-screen fragments in advance to make the animation look smooth when change the tab.
Because of this, the ads was getting loaded without clicking on the second tab. However, you can change the number of off screen fragments to load by using viewPager.setOffscreenPageLimit but its default and minimum value is 1. If you set it to 1, your second tab will be created in advance but not the third one.
To load ads on selection of second tab, you have to use ViewPager's pageChangeListener and check if second tab got selected, show the Ads.
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if(position == 1)
displayInterstitial();
}
});
And don't forget to remove ((MainActivity)getActivity()).displayInterstitial(); from the fragment.

Categories