I have problem with sharedElementTransitions. I have one activity with fragment - from this fragment I start new activity with sharedElementTransitions, inside this activity I start fragment and inside this fragment is viewPager, now when I call setTransitionName in this fragment everything works very well, but when I move it to fragment that is inside my viewPager and call it inside onCreateView there is no smooth enter animation, back animation is working as intended. I was quite sure this might be resolved using postponeEnterTransition, so in my activity with fragment with viewPager I am calling postponeEnterTransition() and in my fragment getActivity().startPostponedEnterTransition() but it is still not working... Any ideas what might go wrong?
// Postpone the shared element enter transition in onCreate()
postponeEnterTransition();
// after the layout and data is ready, invoke startPostponedEnterTransition() to start the enter transition animation
// for example:
sharedElement.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
sharedElement.getViewTreeObserver().removeOnPreDrawListener(this);
startPostponedEnterTransition();
return true;
}
});
Please refer to : http://www.androiddesignpatterns.com/2015/03/activity-postponed-shared-element-transitions-part3b.html for more details
Hope it will be helpful!
Related
I write a ViewPager with some Fragments. In the Fragment, there are VideoView. At the beginning, the first VideoView will auto play, when the first VideoView finishes, I want change the page of VideoView, so I want call setCurrentItem in Fragment. Is this possible?
you can use eventbus notice viewpager to next page.
implement toNextPage func
void toNextPage() {
if (viewPager.getAdapter().getCount() >= viewPager.getCurrentItem() + 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
Toast.makeText(this, "is end", Toast.LENGTH_SHORT).show();
}
}
As you've not mentioned the language you're using, I'm gonna answer it for both Java and Kotlin.
Java:
Create a function in your ViewPager's Activity as
public void changeViewPagerPostition(int position) {
viewPager.setCurrentItem(position);
}
And call this function it from Fragment with passing the postition parameter as
((YourActivity) getActivity()).changeViewPagerPostition(yourPostition);
//Remember first item is at 0th postition and so on.
You can also declare the ViewPager as public static in your Activity and can access the ViewPager directly in Fragment but this is not the preferred way.
Kotlin:
In kotlin, it's a bit easy I believe, although you can use exact same way mentioned for Java but I use this way as I also use ViewPager for more things:
Declare the ViewPager as global variable in your Activity as
lateinit var viewPager : ViewPager
Initialize in it onCreate() of the Activity as
viewPager = findViewById(R.id.viewPager)
And use it in fragment and pass your current postition as
(activity as YourActivity?)!!.setCurrentItem(yourPosition)
Now, the moment your video finishes, you can call any of these ways in your Fragment to change the currentItem of the ViewPager.
Problem:
I am currently running into a problem where my app is trying to load too many fragments when it opens for the first time.
I have BottomNavigationView with ViewPager that loads 4 fragments - each one of the Fragment contains TabLayout with ViewPager to load at least 2 more fragments.
As you can imagine, that is a lot of UI rendering (10+ fragments) - especially when some of these fragments contain heavy components such as calendar, bar graphs, etc.
Currently proposed solution:
Control the UI loading when the fragment is required - so until the user goes to that fragment for the first time, there is no reason to load it.
It seems like it's definitely possible as many apps, including the Play Store, are doing it. Please see the example here
In the video example above - the UI component(s) are being loaded AFTER the navigation to the tab is completed. It even has an embedded loading symbol.
1) I am trying to figure out how to do exactly that - at what point would I know that this fragment UI need to be created vs it already is created?
2) Also, what is the fragment lifecycle callback where I would start the UI create process? onResume() means UI is visible to the user so loading the UI there will be laggy and delayed.
Hope this is clear enough.
EDIT:
I'm already using the FragmentStatePagerAdapter as ViewPager adapter. I noticed that the super(fm) method in the constructor is deprecated now:
ViewPagerAdapter(FragmentManager fm) {
super(fm); // this is deprecated
}
So I changed that to:
ViewPagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT: Indicates that only the current fragment will be in the Lifecycle.State.RESUMED state. All other Fragments are capped at Lifecycle.State.STARTED.
This seems useful as the onResume() of the Fragment will only be called when the Fragment is visible to the user. Can I use this indication somehow to load the UI then?
The reason your app loads multiple Fragments at the startup is most probably, you're initializing them all at once. Instead, you can initialize them when you need them. Then use show\ hide to attach\ detach from window without re-inflating whole layout.
Simple explanation: You'll create your Fragment once user clicks on BottomNavigationView's item. On clicked item, you'll check if Fragment is not created and not added, then create it and add. If it's already created then use show() method to show already available Fragment and use hide() to hide all other fragments of BottomNavigationView.
As per your case show()/hide is better than add()/replace because as you said you don't want to re-inflate the Fragment when you want show them
public class MainActivity extends AppCompatActivity{
FragmentOne frg1;
FragmentTwo frg2;
#Override
public boolean onNavigationItemSelected(MenuItem item){
switch(item.getId()){
case R.id.fragment_one:
if (frg2 != null && frg2.isAdded(){
fragmentManager.beginTransaction().hide(frg2).commit();
}
if(frg1 != null && !frg1.isAdded){
frg1 = new FragmenOne();
fragmentManager.beginTransaction().add(R.id.container, frg1).commit();
}else if (frg1 != null && frg1.isAdded) {
fragmentManager.beginTransaction().show(frg1).commit();
}
return true;
case R.id.fragment_two:
// Reverse of what you did for FragmentOne
return true;
}
}
}
And for your ViewPager as you can see from the example you're referring to; PlayStore is using setOffscreenPageLimit. This will let you choose how many Views should be kept alive, otherwise will be destroyed and created from start passing through all lifecycle events of the Fragment (in case view is Fragment). In PlayStore app's case that's probably 4-5 that why it started loading again when you re-selected "editor's choice" tab. If you do the following only selected and neighboring (one in the right) Fragments will be alive other Fragments outside screen will be destroyed.
public class FragmentOne extends Fragment{
ViewPager viewPager;
#Override
public void onCreateView(){
viewPager = .... // Initialize
viewpAger.setOffscreenPageLimit(1); // This will keep only 2 Fragments "alive"
}
}
Answer to both questions
If you use show/hide you won't need to know when to inflate your view. It will be handled automatically and won't be laggy since it's just attaching/detaching views not inflating.
It depends upon how you initialize your fragment in your activity. May be you are initializing all your fragment in onCreate method of your activity instead of that you can initialize it when BottomNavigation item is selected like below :
Fragment one,two,three,four;
#Override
public boolean onNavigationItemSelected(MenuItem item){
Fragment fragment;
switch(item.getId()){
case R.id.menu_one:{
if(one==null)
one = Fragment()
fragment = one;
break;
}
case R.id.menu_two:{
if(two==null)
two = Fragment()
fragment = two;
break;
}
}
getFragmentManager().beginTransaction().replace(fragment).commit();
}
To decide how many page is load in you view pager at one time you can use :
setOffscreenPageLimit.
viewPager.setOffscreenPageLimit(number)
To get the resume and pause functionality on fragments you can take an example from this link.
Please try this.
i was worked with the same kind of the Application, There were multiple tabs and also Tabs have multiple inner tabs.
i was used the concept of ViewPager method, In which there is one method of onPageSelected() for that method we were getting the page position.
By the Use of this position we are checking the current Fragment and called their custom method that we created inside that fragment like onPageSelected() defined inside that fragment.
With this custom method onPageSelected() inside the Fragment we checked that weather the list are available or not if list have data then we are not making the call of Api otherwise we are calling the Api and loading that list.
I think you have same kind of requirement to follow if your Tabs have inner Tab or viewpager you can follow same concept inside of that so if your current fragment of viewpager method onpageSelected called at that time your viewpager fragment initialized.
you have to call just initialization like data binding or view initialization need to be called in onCreate() method and other list attachment and api call to be managed by the custom method onPageSelected that will be called based on ViewPager onPageSelected.
let me Know if you need any help for same.
You can try to have Fragments with FrameLayouts only in ViewPager. The actual Fragments could be added to FrameLayout in onResume() (after checking if this Fragment isn't already attached). It should work if BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT works as expected.
I would recommend you use BottomNavigationView.setOnNavigationItemSelectedListener to toggle between the fragment UI whenever it is needed.
navigationView.setOnNavigationItemSelectedListener(item -> {
switch(item.getItemId()) {
case R.id.item1:
// you can replace the code findFragmentById() with findFragmentByTag("dashboard");
// if you only have one framelayout to hold the fragment
fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new ExampleFragment();
// if the fragment is identified by tag, add another
// argument to this method:
// replace(R.id.fragment_container, fragment, "dashboard")
getSupportFragmentManager().begintransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
break;
}
}
The idea is simple, when the user swipes or selects a different tab, the fragment that was visible is replaced by the new fragment.
Just load fragments one by one. Create the main fragment layout with many placeholders and stubs and then just load them in the order you like.
Use FragmentTransaction.replace() from the main fragment after it loads.
Have you tried the setUserVisibleHint() method of a fragment
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if(isVisibleToUser){
// Do you stuff here
}
}
This will only get called when a fragment is visible to the user
How about you maintain just one ViewPager? Sounds crazy? In that case, you just change the dataset of PagerAdapter when you switch between the bottom tabs. Let's see how you can accomplish this,
As you mentioned, you have 4 fragments, which are assigned to each individual tabs of the bottom navigation view. Each performs some redundant work i.e. holding a viewPager with tab layout and setting the same kind of adapters. So, if we can combine these 4 redundant tasks into one then we will be able to get rid of 4 fragments. And as there will be just one viewPager with one single adapter then we will be able to reduce the fragment loading count from ~10 to 2 if we set offScreenPageLimit to 1. Let's see some example,
activity.xml should look like
<LinearLayout>
<TabLayout />
<ViewPager />
<BottomNavigationView />
</LinearLayout>
It's optional but I would recommend to create a base PagerFragment abstract class with abstract method getTabTitle()
public abstract class PagerFragment extends Fragment {
public abstract String getTabTitle();
}
Now it's time to make our PagerAdapter class
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public Map<Integer, List<PagerFragment>> map = ...; // If you are concerned about memory then I could recommend to store DataObject instead of PagerFragment and instantiate fragment on demand using that data.
public int currentTabId = R.id.first_bottom_tab_id;
private List<PagerFragment> getCurrentFragments() {
return map.get(currentTabId);
}
public void setCurrentTabId(int tabId) {
this.currentTabId = tabId;
}
public SectionsPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return getCurrentFragments().get(position);
}
#Override
public int getCount() {
return getCurrentFragments().size();
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return getCurrentFragments().get(position).getTabTitle();
}
}
And finally, in Activity
SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(1);
viewPagerTab.setViewPager(viewPager);
bottomNavigationView.setOnNavigationItemSelectedListener(menuItem -> {
pagerAdapter.setCurrentTabId(menuItem.getItemId())
pagerAdapter.notifyDataSetChanged();
viewPagerTab.setViewPager(viewPager);
}
This is the basic idea. You can mix some of your own ideas with it to make a wonderful result. Let me know if it is useful?
UPDATE
Answer to your questions,
I think with my solution you can achieve exactly the same behavior of the video as I already did it in a project. In my solution, if you set offset page limit to 1 then only adjacent fragment's is created in advance. So, fragment creation will be handled by adapter and viewpager you don't need to worry about it.
In my above solution, you should create UI in onCreateView().
Problem in short:
I have an MainActivity that holds BottomNavigationView and FrameLayout on top of it. BottomNavigationView has 5 tabs and when tab is clicked, I add some fragment on that FrameLayout. But, from some fragment, I need to open another fragment. From that another fragment, I need to open the other one. Every time when I need to show fragment, I notify MainActivity from fragment, that it needs to add the another one. Every fragment checks does its activity implement interface. And it is annoying. So, if I have 100 fragments, MainActivity implements too many interfaces. It leads to boilerplate code. So, how to properly navigate between fragments if you have a lot?
Problem in detail:
Please, read problem in short section first.
As I've said I have BottomNavigationView that has 5 tabs. Let's call the fragments that responsible for each tab as FragmentA, FragmentB, FragmentC, FragmentD, FragmentE. I really know, how to show these fragments when tab is clicked. I just replace/add these fragments in activity. But, wait, what if you wanna go from FragmentA to FragmentF? After that from FragmentF to FragmentG? This is how I handle this problem: from FragmentF or FragmentG I notify MainActivity that I wanna change the fragment. But how they communicate with MainActivity? For this, I have interfaces inside of each fragment. MainActivity implements those interfaces. And here is problem. MainActivity implements too many interfaces that leads to boilerplate code. So, what is the best way to navigate through Fragments? I don't even touch that I also need to handle back button presses :)
Here is how my code looks like:
MainActivity implementing interfaces to change fragments if necessary:
class MainActivity : AppCompatActivity(), DashboardFragment.OnFragmentInteractionListener,
PaymentFragment.BigCategoryChosenListener, PaymentSubcategoryFragment.ItemClickedListener, PayServiceFragment.OnPayServiceListener, ContactListFragment.ContactTapListener, P2PFragment.P2PNotifier
Here is my PaymentFragment's onAttach method for example:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof BigCategoryChosenListener) {
listener = (BigCategoryChosenListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement BigCategoryChosenListener");
}
}
And using this listener I notify activity to change fragment. And in EACH fragment I should do so. I don't think that it is best practice. So, is it ok or there is a better way?
Ok What you need is something like this in activity where you would initialized on your BottomNavigationView.
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_1://Handle menu click -
//Call Navigator helper to replace Fragment to Fragment A
break;
case R.id.menu_2:
//Call Navigator helper to replace Fragment to Fragment B
break;
case R.id.menu_3:
//Call Navigator helper to replace Fragment to Fragment C
break;
}
return true;
}
});
In my app, I have an Activity launching another Activity with a Fragment in it, that contains a ViewPager of images. What I have working currently, is the enter transition where the first Activity launches the second and the transition is correct. This works because, in my ViewPager I put a OnPreDrawListener on it and only resume the activity transition when the image in the pager is loaded. It looks like this:
public class ImagePagerAdapter extends PagerAdapter {
// Constructor and other things..
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView;
if (position == 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Shared element is the first one.
ViewCompat.setTransitionName(imageView, "sharedImage");
}
}
imageView = new ImageView(activity);
// Just a reusable static Helper class.
HelperPicasso.loadImage(images.get(position), imageView, false, new Callback() {
#Override
public void onSuccess() {
imageView.getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
imageView.getViewTreeObserver()
.removeOnPreDrawListener(this);
// When the ImageView is ready to be drawn, we can continue our activity/fragment's postponed transition animation.
// Why? Because we want have the first image be the shared element, and we can only set it after instantiation.
ActivityCompat.startPostponedEnterTransition(activity);
return true;
}
});
}
#Override
public void onError() {
ActivityCompat.startPostponedEnterTransition(activity);
}
});
}
}
Aside from the ImageView, I also have a FrameLayout which is a shared element as well, but I mark it with it's transition name in the onCreateView of the fragment.
With this the enter transition works well for me. However, when I press the back button, the FrameLayout's exit transitions works correctly, but the ViewPager image goes blank.
My guess is that the fragment's lifecycle causes the ViewPager (and it's child views) to be destroyed during the exit transition.
I've tried adding ActivityCompat.finishAfterTransition(this) in the onBackPressed callback for the parent Activity, but it doesn't seem to have any effect.
When you have a ViewPager in the middle of a transition then you have to do some extra work in order to have a fluid and "beautiful" transition. You must play with postponeTransition() and startPostponedTransition() in order to play the transitions only when fragments or images finished to load. (It seems that you are already doing it). I recommend you to you to check the next blog: Shared Element Transitions - Part 4: RecyclerView
The target of that article is more RecyclerView + ViewAdapter + Fragments transitions but I´m sure you can adapt it in your scenario. Hope it helps.
I have a Viewpager that uses a FragmentStatePagerAdapter. Each page is a Fragment. My pages contains an linearlayout (llTags) which is default visible.
If the user clicks on a page (main layout of the fragment), the linearlayout must be invisible (works) but the other linearlayouts (llTags in other pages) needs to be changed too.
If i click, the visibility of the linearlayouts changed off all pages exept the previous and next.
This is because the getItem from the adapter isn't called for the next/previous item again.
How can i notify these pages.
ps: i have a newInstance method and a public void setTagslayoutVisible(boolean) for changing the visibility from the adapter.
Next and previous are already loaded and the adapter is not going to call creation.
Take a quick try at this, in your adapter get function if your fragment is already loaded it returns those objects. So just add something like this
if(myMap.containsKey(position))
{
LiveStreamFullScreenFragment lfsf = (LiveStreamFullScreenFragment) myMap.get(position));
lfsf.setShowTags(mShowTags);
return lfsf;
} else
{
and in your fragment class
public void setShowTags(boolean showtags)
{
mShowTags = showtags;
if(!mShowTags)
{
llLiveStreamTags.setVisibility(View.GONE);
}
}
Hope this helps and enjoy your work.