I'm trying to start an animation when the fragment is showed on screen(I'm working with a ViewPager).
This a part of my code
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
mFragmentTags = new HashMap<Integer, String>();
}
public ScreenSlidePageFragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null)
return null;
return (ScreenSlidePageFragment) mFragmentManager.findFragmentByTag(tag);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
// record the fragment tag here.
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
System.out.println("holi");
}
return obj;
}
}
public class ScreenSlideActivity extends FragmentActivity {
(...)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
(...)
SimpleOnPageChangeListener mPageChangelistener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When changing pages, reset the action bar actions since they are dependent
// on which page is currently active. An alternative approach is to have each
// fragment expose actions itself (rather than the activity exposing actions),
// but for simplicity, the activity provides the actions in this sample.
ScreenSlidePageFragment currentFgm = mPagerAdapter.getFragment(position);
Animation animacion = AnimationUtils.loadAnimation(ScreenSlideActivity.this, R.anim.glasses);
currentFgm.getView().findViewById(R.id.image).startAnimation(animacion);
invalidateOptionsMenu();
}
(...)
The problem is when onPageSelected is called returns a NullPointer Exception in
currentFgm.getView().findViewById(R.id.image).startAnimation(animacion);
How could I start the animation when the fragment is showed on screen?
If you are trying to add animation to the ViewPager then you can implement the ViewPager.PageTransformer interface and supply it to the view pager to display a different animation than the default screen slide animation.
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
...
mPager.setPageTransformer(true, new CustomTransformer());
You will find here two examples of PagerTransformers.
Related
I'm using nested FragmentStatePagerAdapter on my single activity application. The current layout is:
Activitiy
- Login Fragment
- Master Fragment
- Tab Fragment #1
- Tab Fragment #2
- Tab Fragment #3
- Another Fragment
- Another Fragment
Everytime i switch back from "Another Fragment" into "Master Fragment" the FragmentStatePagerAdapter instante the same item twice for example
First Time: Tab Fragment #1 #2 #3
Second Time: Tab Fragment #1 #1 #2 #2 #3 #3
Third Time: Tab Fragment #1 #1 #1 #2 #2 #2 #3 #3 #3.
To move from fragment to fragment i use
getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content, XXXX.newInstance(query), TAG_XXX)
.addToBackStack(null)
.commit();
The MasterFragment code:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initFragmentAdapter();
}
private void initFragmentAdapter() {
final FragmentSimpleAdapter adapter = new FragmentSimpleAdapter(getChildFragmentManager());
adapter.addFragment(
getString(...),
"...",
XXX.class);
...
ViewPager viewPager = (ViewPager) getActivity().findViewById(android.R.id.tabcontent);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(4);
PagerSlidingTabStrip viewTabs = (PagerSlidingTabStrip) getActivity().findViewById(
android.R.id.tabhost);
viewTabs.setViewPager(viewPager);
viewTabs.setOnPageChangeListener(adapter);
}
private final class FragmentSimpleAdapter extends FragmentStatePagerAdapter
implements ViewPager.OnPageChangeListener {
private final List<String> mTitles = new LinkedList<>();
private final List<String> mInstances = new LinkedList<>();
private final List<String> mTag = new LinkedList<>();
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
public FragmentSimpleAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
mFragmentTags = new HashMap<>();
}
#Override
public int getCount() {
return mTitles.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mTitles.get(position);
}
#Override
public Fragment getItem(int position) {
return Fragment.instantiate(getActivity(), mInstances.get(position), null);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null) {
return null;
}
return mFragmentManager.findFragmentByTag(tag);
}
public FragmentSimpleAdapter addFragment(String title, String tag,
Class<? extends Fragment> fragment) {
mTitles.add(title);
mTag.add(tag);
mInstances.add(fragment.getName());
return this;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Analytics.sendViewAnalytic(mTag.get(position))
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
problem:
PagerSlidingTabStrip viewTabs = (PagerSlidingTabStrip) getActivity().findViewById(
android.R.id.tabhost);
You are trying to re create and re create PagerSlidingTabStrip everytime you go back inside your Master's Fragment thus adding unnecessary fragment.
solution:
you need to check first if the tab already exist I dont really know about that PagerSlidingTabStrip I think it is a custom made class.
When you nest fragments inside fragments, you should instantiate the FragmentStatePagerAdapter using getChildFragmentManager and not getFragmentManager.
Fixed by moving the FragmentSimpleAdapter initialization code from onActivityCreate to onCreate
Well, Consider I have have two fragments FragmentTab1 & ShowAllContactFragment. FragmentTab1 consists a list-view & and a button. When the button is clicked I replace ShowAllContactFragment in my viewpager. When shows ShowAllContactFragment, user can select several contacts by selecting check-box in a list-view & it also has a ADD contact button.
What I need: I want to update existing listview in FragmentTab1 , when user pressing ADD button in ShowAllContactFragment, after selecting some contacts in this list-view. I also remove ShowAllContactFragment, and show FragmentTab1 when this will occur.
My Solving Status: I follow the the android developers forum to communicate data between fragment via Activity. I'm almost done. I create Interface OnContactSelectedListener in ShowAllContactFragment & Implements in MainActivity. Everything is ok! . After debugging, I check my callback methods that I have data in MainActivity but I can't replace the ShowAllContactFragment & can't show the previous fragment FragmentTab1 & update it's list-view.
To open ShowAllContactFragment from FragmentTab1, I wrote like:
ShowAllContactFragment allContactsFragment = new ShowAllContactFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.add(R.id.fragmentTabLayout1, allContactsFragment);
transaction.commit();
My MainActivity & FragmentAdapter Looks :
public class MainActivity extends SherlockFragmentActivity implements
ShowAllContactFragment.OnContactSelectedListener {
ActionBar.Tab Tab1, Tab2, Tab3, Tab4;
private Context context = this;
// view pager
// Declare Variables
ActionBar actionBar;
ViewPager mPager;
Tab tab;
FragmentAdapter mAdapter;
List<Fragment> fragmentList = new ArrayList<Fragment>();
ArrayList<Person> blackListPersonList;
private final static String TAG_FRAGMENT = "TAG_FRAGMENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set application in portrait mode
ActivityHelper.initialize(this);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
addFragmentsInList();
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// add an adapter to pager
mAdapter = new FragmentAdapter(getSupportFragmentManager(), mPager,
actionBar, fragmentList);
mPager.setAdapter(mAdapter);
addActionBarTabs();
}
public void addFragmentsInList() {
FragmentTab1 aFragmentTab1 = new FragmentTab1();
fragmentList.add(new FragmentTab1());
fragmentList.add(new FragmentTab2());
fragmentList.add(new FragmentTab3());
}
private void addActionBarTabs() {
String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
for (String tabTitle : tabs) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
.setTabListener(tabListener);
actionBar.addTab(tab);
}
}
private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// add action menu here
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_itemlist, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.add_item:
// openSearch();
Toast.makeText(context, " add_item ", Toast.LENGTH_SHORT).show();
return true;
case R.id.about:
// composeMessage();
Toast.makeText(context, " about", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class FragmentAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
final int TOTAL_PAGES = 3;
private List<Fragment> fragments;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public FragmentAdapter(FragmentManager fm, ViewPager pager,
ActionBar actionBar, List<Fragment> fragmentsList) {
super(fm);
this.mViewPager = pager;
this.mViewPager.setOnPageChangeListener(this);
this.fragments = fragmentsList;
}
#Override
public Fragment getItem(int position) {
// switch (position) {
// case 0:
// return FragmentTab1.newInstance();
// case 1:
// return FragmentTab2.newInstance();
// case 2:
// return FragmentTab3.newInstance();
// default:
// throw new IllegalArgumentException(
// "The item position should be less or equal to:"
// + TOTAL_PAGES);
// }
return this.fragments.get(position);
}
#Override
public int getCount() {
// return TOTAL_PAGES;
return this.fragments.size();
}
public ViewPager getViewPager() {
return mViewPager;
}
// added newly
#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);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
#Override
public void onBackPressed() {
Log.e(TAG_FRAGMENT, "onBackPressed");
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
#Override
public void onContactSelected(ArrayList<Person> contactNumberlist) {
// data comes here, no problem.
this.blackListPersonList = contactNumberlist;
Log.d("onContactSelected", "onContactSelected");
// get error here
FragmentTab1 aFragmentTab1 = (FragmentTab1) mAdapter.getItem(0);
if (aFragmentTab1 != null) {
aFragmentTab1.updateFragment1(blackListPersonList);
}
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_all_contacts_layout, aFragmentTab1);
transaction.commit();
}
public ArrayList<Person> getBlackListContacts() {
return blackListPersonList;
}
// public Fragment getFragment(ViewPager pager){
// Fragment theFragment = fragments.get(pager.getCurrentItem());
// return theFragment;
// }
}
FrgmentTab1 looks :
public class FragmentTab1 extends SherlockFragment implements OnClickListener {
Button btnTest;
ViewPager pager;
LinearLayout layoutBlockNumbers;
LinearLayout layoutContact, layoutCallLog, layoutSMSLog, layoutManually;
public Context mContext;
CustomizedDialog dialog;
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final double RESULT_OK = -1;
ListView listViewOnlyBlackListNumber;
ArrayList<Person> personList;
BlackListAdapter aBlackListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
layoutBlockNumbers = (LinearLayout) rootView
.findViewById(R.id.layoutAddBlockNumbers);
layoutBlockNumbers.setOnClickListener(this);
listViewOnlyBlackListNumber = (ListView) rootView
.findViewById(R.id.listViewOnlyBlackListNumber);
personList = ((MainActivity) getActivity()).getBlackListContacts();
if (personList != null) {
aBlackListAdapter = new BlackListAdapter(getActivity(), personList,
m_onSelectedEventCalender);
listViewOnlyBlackListNumber.setAdapter(aBlackListAdapter);
} else {
listViewOnlyBlackListNumber.setEmptyView(container);
}
return rootView;
}
public void updateFragment1(ArrayList<Person> personList) {
// trying to update when came back here
aBlackListAdapter = new BlackListAdapter(getActivity(), personList,
m_onSelectedEventCalender);
listViewOnlyBlackListNumber.setAdapter(aBlackListAdapter);
aBlackListAdapter.notifyDataSetChanged();
}
}
Get Error In onContactSelected, inside MainActivity
10-30 00:22:29.674: E/AndroidRuntime(26834): FATAL EXCEPTION: main
java.lang.IllegalStateException: Can't change container ID of fragment FragmentTab1{42d27380 #0 id=0x7f040032 android:switcher:2130968626:0}: was 2130968626 now 2130968638
E/AndroidRuntime(26834): at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:407)
E/AndroidRuntime(26834): at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:384)
E/AndroidRuntime(26834): at com.mobigic.callblocker.MainActivity.onContactSelected(MainActivity.java:240)
Hope, Somebody help me.
Your question is not very clear especially the part about how you handle those fragments. Like when you're showing the ShowAllContactFragment fragment in which layout do you put it? From the code you posted it seems you're blindly adding the ShowAllContactFragment fragment directly in the layout containing the ViewPager which isn't right.
Related to the error, you get a reference to one of the fragments already managed by the FragmentManager through the adapter of the ViewPager and then you retry to add it in a transaction, action which will fail. If you're trying to show the previous shown FragmentTab1 fragment, after showing and working with the ShowAllContactFragment fragment, you should try simply removing the last recorded action of the FragmentManager through one of its popBackStack...() methods.
Edit: I looked at your code but what you're doing is still ambiguous. I've looked at the layout for the main activity but you don't have a container with the id R.id.fragment_all_contacts_layout so I'm assuming you're somehow trying to insert the new FragmentTab1 in the layout of the old FragmentTab1 which really doesn't make any sense(not to mention you add the ShowAllContactFragment to a container with the id R.id.fragmentTabLayout1 which I also can't see). Anyway, I'm assuming that you want the ShowAllContactFragment to replace the FragmentTab1 from the ViewPager. For this you'll need a wrapper fragment to hold the two nested fragment and also enable the communication between them. For example the wrapper fragment:
public static class WrapperFragment extends Fragment implements
OnContactSelectedListener {
private static final String TAG_FIRST = "tag_first";
private static final String TAG_SECOND = "tag_second";
private static final int CONTENT_ID = 1000;
private FragmentTab1 mFrag1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FrameLayout content = new FrameLayout(getActivity());
content.setId(CONTENT_ID);
if (getChildFragmentManager().findFragmentByTag(TAG_SECOND) == null) {
mFrag1 = (FragmentTab1) getChildFragmentManager()
.findFragmentByTag(TAG_FIRST);
if (mFrag1 == null) {
mFrag1 = new FragmentTab1();
getChildFragmentManager().beginTransaction()
.add(CONTENT_ID, mFrag1, TAG_FIRST).commit();
}
}
return content;
}
#Override
public void onContactSelected(List<Person> contactNumberlist) {
getChildFragmentManager().popBackStackImmediate();
mFrag1.updateFragment1(contactNumberlist);
}
public void showPickerfragment() {
getChildFragmentManager().beginTransaction()
.replace(CONTENT_ID, new ShowAllContactFragment())
.addToBackStack(null).commit();
}
}
This will be the fragment that you'll use in the ViewPager's adapter instead of the FragmentTab1 fragment. Notice that it implements the OnContactSelectedListener interface. You'll also need to make some changes to other parts of the code:
#Override
public void onClick(View v) {
if (v == layoutCallLog) {
dialog.dismiss();
// make the wrapper fragment to open the ShowAllContactFragment fragment
((WrapperFragment) getParentFragment()).showPickerfragment();
// rest of the code
The ShowAllContactFragment will need to be modified to send the selection event to the wrapper fragment which implements its interface:
#Override
public void onClick(View v) {
if (v == btnAdd) {
Toast.makeText(getActivity(), "" + blockListedPersonList.size(),
Toast.LENGTH_SHORT).show();
((OnContactSelectedListener) getParentFragment())
.onContactSelected(blockListedPersonList);
}
}
And in the main activity to handle the BACK button when the ShowAllContactFragment is showing in the ViewPager:
#Override
public void onBackPressed() {
if (mViewPager.getCurrentItem() == 0) { // I assumed 0 is the position in the adapter where the WrapperFragment will be used
Fragment targetPage = getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + PAGER_ID + ":" + 0); // PAGER_ID is the id of the ViewPager
if (targetPage.getChildFragmentManager().getBackStackEntryCount() > 0) {
targetPage.getChildFragmentManager().popBackStack();
}
return;
}
super.onBackPressed();
}
Keep in mind that you'll need to save the data of the nested fragments.
I used FragmentActivity and ViewPager in differents projects and there are two solutions:
1: You can use onHiddenChanged(boolean hidden) method on your FragmentTab1.
override fun onHiddenChanged(hidden: Boolean) {
// TODO Auto-generated method stub
if (!hidden) {
// check if personList size is changed
// and then call updateFragment1() methode
}
super.onHiddenChanged(hidden)
}
2: Use a static method: you can ake updateFragment1() method static so when user pressing "ADD", call updateFragment1().
Hope it helps.
I have a ViewPager with a FragmentPageAdapter. When a fragment is displayed, I want it to start an animation (fade-in a view in the fragment).
However, the animation runs inconsistently, it runs on every few pages when I swipe left/right. I think I need to start the animation on the onPageSelected event but I can't figure out how to get the fragment and start the animation.
My code is below. TourFragment is the fragment I add to the ViewPager using the FragmentPageAdapter while TourActivty contains the ViewPager.
TourFragment
public class TourFragment extends Fragment {
Tour tour;
ImageView ivTitle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tour,
container, false);
RelativeLayout rlImageContainer = (RelativeLayout) v.findViewById(R.id.tour_image_container);
Resources resources = getActivity().getResources();
ivTitle = (ImageView) v.findViewById(R.id.tour_title);
ivTitle.setImageDrawable(resources.getDrawable(tour.getDrawableTitleId()));
Animation fadeInAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.fadein);
ivTitle.startAnimation(fadeInAnimation );
return v;
}
#Override
public void onResume() {
super.onResume();
Animation fadeInAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.fadein);
ivTitle.startAnimation(fadeInAnimation );
}
public static Fragment newInstance(Tour tour) {
TourFragment f = new TourFragment();
f.tour = tour;
return f;
}
}
TourActivity
public class TourActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
String tourType;
Drawable drawableSelected;
Drawable drawableNotSelected;
LinearLayout llIndicators;
int prevPagePosition = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
List<Tour> tours = new ArrayList<Tour>();
messages = getResources().getStringArray(R.array.guess_tour_messages);
Tour tour = new Tour();
tour.setDrawableImageId(R.drawable.tu_guest_image_1);
tour.setDrawableTitleId(R.drawable.tu_guest_text_1);
tour.setMessage(messages[0]);
tour.setPageIndex(0);
tour.setTotalPages(messages.length);
tours.add(tour);
tour = new Tour();
tour.setDrawableImageId(R.drawable.tu_guest_image_2);
tour.setDrawableTitleId(R.drawable.tu_guest_text_2);
tour.setMessage(messages[1]);
tour.setPageIndex(1);
tour.setTotalPages(messages.length);
tours.add(tour);
tour = new Tour();
tour.setDrawableImageId(R.drawable.tu_guest_image_3);
tour.setDrawableTitleId(R.drawable.tu_guest_text_3);
tour.setMessage(messages[2]);
tour.setPageIndex(2);
tour.setTotalPages(messages.length);
tours.add(tour);
tour = new Tour();
tour.setDrawableImageId(R.drawable.tu_guest_image_4);
tour.setDrawableTitleId(R.drawable.tu_guest_text_4);
tour.setMessage(messages[3]);
tour.setPageIndex(3);
tour.setTotalPages(messages.length);
tours.add(tour);
for (Tour tour : tours) {
fList.add(TourFragment.newInstance(tour));
}
return fList;
}
}
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();
}
}
You should use in your fragment
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Log.v(TAG, "run now");
Animation animationFadeIn = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_view);
iv.startAnimation(animationFadeIn);
animationFadeIn.setFillAfter(true);
}
else { }
}
I figured it out.
On onPageSelected, I used getView from the fragment to get the view that I want to animate.
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int position) {
View v = pageAdapter.getItem(position).getView();
ImageView ivTitle = (ImageView) v.findViewById(R.id.tour_title);
Animation fadeInAnimation = AnimationUtils.loadAnimation(TourActivity.this, R.anim.fadein);
ivTitle.startAnimation(fadeInAnimation );
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
Inside of your FragmentPagerAdapter implementation you you need to override public Object instantiateItem(viewGroup container, int index). In the base class fragments are only added with a FragmentManager instance when the adapter is first created. Whenever you page away the offscreen fragments are detached but not removed. The FragmentManager caches the instances with a tag on the object. They are then attached when they are paged back to. The default implementation of instantiateItem item tags each Fragment inside of the FragmentAdapter with a hardcoded tag. You need to tag each Fragment you use with a unique tag. With this is place you can retrieve fragment instances from any FragmentManager instance in your app with public abstract Fragment findFragmentByTag (String tag).
String[] tags = {"tag1", "tag2", "tag3", "tag4", "tag5"};
#Override
public Object instantiateItem(ViewGroup container, int index) {
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = fm.findFragmentByTag(tags[index]);
if (fragment == null) {
fragment = getItem(index);
ft.add(container.getId(), fragment, mTags[index]);
}
else {
ft.attach(fragment);
}
ft.commit();
return fragment;
}
public String getTag(int index) {
return mTags[index];
}
You should be able to access the the instances in onPageSelected now.
I had a similar problem and here what solved it:
Animation of nested fragment within ViewPager fragment is triggered before render
In context of your case the same solution would look like this:
java:
v.post(new Runnable() {
#Override
public void run() {
ivTitle.startAnimation(fadeInAnimation)
}
})
kotlin:
v.post(Runnable {
ivTitle.startAnimation(fadeInAnimation)
})
It ensures that the view is indeed drawn
i have an activity with actionbarsherlock TabsNavigation (3 tabs) and when I press a tab i change the viewpager adapter of the corresponding fragment. it is working fine, the thing is that when I click on another tab besides the first created, the first page is always the one of that first tab. I tried to put invalidate() before changing the adapter, but it isnt working. anyone has any idea? here is the code:
public class Tabsteste2 extends SherlockFragmentActivity implements TabListener {
static AdapterOpiniao mOdapter;
static AdapterDados mDdapter;
static AdapterFoto mFdapter;
Bundle extras;
JSONParser jsonParser = new JSONParser();
SharedPreferences mPrefs;
static ViewPager mPager;
static int countopiniao;
static int countdados;
static int countfoto;
JSONArray perguntas = null;
PageIndicator mIndicator;
static ArrayList<HashMap<String, String>> opiniaolist;
static ArrayList<HashMap<String, String>> dadoslist;
static ArrayList<HashMap<String, String>> fotolist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabsteste2);
opiniaolist = new ArrayList<HashMap<String, String>>();
dadoslist = new ArrayList<HashMap<String, String>>();
fotolist = new ArrayList<HashMap<String, String>>();
mPager = (ViewPager)findViewById(R.id.pager);
extras = getIntent().getExtras();
Boolean opiniaoflag = extras.getBoolean("opiniaoflag");
Boolean dadosflag = extras.getBoolean("dadosflag");
Boolean fotoflag = extras.getBoolean("fotoflag");
countdados= extras.getInt("countdados");
countopiniao=extras.getInt("countopiniao");
countfoto=extras.getInt("countfoto");
mPrefs = getSharedPreferences("mPrefs1",MODE_PRIVATE);
Log.d("countdados",""+countdados);
Log.d("countfoto",""+countfoto);
Log.d("countopiniao",""+countopiniao);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(opiniaoflag==true){
ActionBar.Tab opiniaotab = getSupportActionBar().newTab();
opiniaotab.setText("OpiniĆ£o");
opiniaotab.setTag("op");
opiniaotab.setTabListener(this);
mOdapter = new AdapterOpiniao(getSupportFragmentManager());
Log.d("Opiniao",""+opiniaotab.getTag());
getSupportActionBar().addTab(opiniaotab);
}if(dadosflag == true){
ActionBar.Tab dadostab = getSupportActionBar().newTab();
dadostab.setText("Dados");
dadostab.setTag("dd");
mDdapter = new AdapterDados(getSupportFragmentManager());
dadostab.setTabListener(this);
Log.d("Dados",""+dadostab.getTag());
getSupportActionBar().addTab(dadostab);
}
// mDdapter = new AdapterDados(getSupportFragmentManager());
if(fotoflag==true){
ActionBar.Tab fotostab = getSupportActionBar().newTab();
fotostab.setText("Fotos");
fotostab.setTag("ft");
mFdapter = new AdapterFoto(getSupportFragmentManager());
fotostab.setTabListener(this);
Log.d("Foto",""+fotostab.getTag());
getSupportActionBar().addTab(fotostab);
}
new getpergunta().execute();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction transaction) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
if(tab.getTag().equals("op")){
mPager.invalidate();
mPager.setAdapter(mOdapter);
mIndicator = (UnderlinePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}else if (tab.getTag().equals("dd")){
mPager.invalidate();
mPager.setAdapter(mDdapter);
mIndicator = (UnderlinePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}else if(tab.getTag().equals("ft")){
mPager.invalidate();
mPager.setAdapter(mFdapter);
mIndicator = (UnderlinePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
}
public static class AdapterOpiniao extends FragmentPagerAdapter {
public AdapterOpiniao(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return countopiniao;
}
#Override
public Fragment getItem(int position) {
return FragmentOpinioes.newInstance(position);
}
}
public static class AdapterDados extends FragmentPagerAdapter {
public AdapterDados(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return countdados;
}
#Override
public Fragment getItem(int position) {
return FragmentDados.newInstance(position);
}
}
public static class AdapterFoto extends FragmentPagerAdapter {
public AdapterFoto(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return countfoto;
}
#Override
public Fragment getItem(int position) {
return FragmentFotos.newInstance(position);
}
}
To solve your case, I used:
#Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
this.mPager.setCurrentItem(tab.getPosition());
}
When a click on a tab, the view of the corresponding tab is automatically changed.
Edit: I must admit that I have some difficulties to really understand your code and what you are trying to do, so I add some more code to explain what i think you need.
In my optinion, only one adapter is necessary for the ViewPager, and then if I'm right, you would do so:
// I took some personal code for my example
private ViewPager mPager;
private PageIndicator mIndicator;
private TabsExampleSectionsAdapter mAdapter;
// Inside the onCreate method
this.mPager = (ViewPager) findViewById(R.id.pager);
this.mIndicator = new TabPageIndicator(this);
this.mAdapter = new TabsExampleSectionsAdapter(this.getSupportFragmentManager());
this.mPager.setAdapter(this.mAdapter);
this.mIndicator.setViewPager(this.mPager);
When everything is initialized, this is how to build tabs and pager views instructions (the two are related). Also, don't mind the Section class, it's a custom data model object which contains the tag data you need but it has nothing to do with actionbarsherlock.
private void buildTabs(Section[] sections) {
if (sections != null) {
for (Section section : sections) {
ActionBar.Tab sectionTab = getSupportActionBar().newTab();
sectionTab.setText(section.name);
sectionTab.setTabListener(this);
getSupportActionBar().addTab(sectionTab);
// The tag ("op" or "dd" in your case for example) is contained somewhere in the section object
this.mAdapter.getSections().add(section);
}
}
}
And finally, this is the view pager adapter. It will choose what type of fragment to return following the tags you defined for each tab position:
public class TabsExampleSectionsAdapter extends FragmentPagerAdapter {
private ArrayList<Section> mSectionsList = new ArrayList<Section>();
public TabsExampleSectionsAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
// Retrieving the cooresponding tag of position
Section section = this.mSectionsList.get(position % getCount());
// Here, you check the tag to know what type of fragment you must return
if (section.getTag().equals("dd")) {
return FragmentDados.newInstance(position);
} else if (section.getTag.equals("op")) {
return FragmentOp.newInstance(position);
}
}
#Override
public int getCount() {
return this.mSectionsList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return this.mSectionsList.get(position % getCount()).name.toUpperCase();
}
public ArrayList<Section> getSections() {
return this.mSectionsList;
}
}
In conclusion, when everything is set up, changing views doesn't have to be done manually by changing adapters and calling invalidate(). You can return different type of fragments from your adapter with a simple condition. Then, by calling:
this.mPager.setCurrentItem(position);
it changes automatically the current view by passing in the adapter's getItem(position) method. Basically, you just have to coordinate your tab positions and your tags in order to get the right type of fragment.
Feel free to ask for more details.
I have a FragmentList with some items. If I click an item the appropriate Fragment will open which contains a Viewpager. No problem so far but if I go back to the List and click the item again the method getItem(int position) is not called anymore.
Here a link with a similar problem:
Display fragment viewpager within a fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_fragment_runtime, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
indicator = (TitlePageIndicator) view.findViewById(R.id.indicator);
MyFragmentPagerAdapter mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
indicator.setViewPager(mViewPager);
return view;
}
class MyFragmentPagerAdapter extends FragmentStatePagerAdapter implements TitleProvider {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public String getTitle(int position) {
return muxbusTitles[position];
}
#Override
public Fragment getItem(int location) {
return muxbusFragmentList.get(location);
}
#Override
public int getCount() {
return muxbusTitles.length;
}
}
return view;
}
Edit:
If someone is interested,the solution was to extends from PagerAdapter instead of FragmentStatePagerAdpater because the Viewpager is already in a Fragment..
I did have similar problem and after scratching my head for quite some time i made an my own understanding (assumption) that ViewPager is keeping the reference of its child fragments into memory even the hosted Fragment or Activity is destroyed (didn't tested with Activity). So i wrote this method freeFragmentsFromViewPager(). You need to call it from onDestroy() of your Fragment.
/**
* This method free the child fragments from ViewPager as ViewPager keeps the reference
* of child fragments into memory and next time when you again come to visit view pager it won't show the fragment layout
* because it has the reference to the fragment whilst the fragment's view was already destroyed.
*/
private void freeFragmentsFromViewPager()
{
for(int i = 0; i < TabsFragmentPagerAdapter.fragments.length; i++)
{
Fragment fragment = TabsFragmentPagerAdapter.fragments[i];
if(fragment != null)
{
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
TabsFragmentPagerAdapter.fragments[i] = null;
}
}
}
And this is my Adapter code
public class TabsFragmentPagerAdapter extends FragmentPagerAdapter
{
public static final int NUM_TABS = 3;
public static Fragment[] fragments = new Fragment[NUM_TABS];
public TabsFragmentPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
Log.e("TabsFragmentPagerAdapter", "getItem");
Fragment fragment = TabsFragmentFactory.newInstace(position);
fragments[position] = fragment;
return fragment;
}
#Override
public int getCount()
{
return NUM_TABS;
}
#Override
public CharSequence getPageTitle(int position)
{
return TabsFragmentFactory.getName(position);
}