How to used a shared transition from RecyclerView to a Fragment - android

I've seen this questioned asked a number of times on here without an answer. I'm hoping if I ask it again maybe someone will be kind enough to help me with it.
I'm trying to implement a shared transition from an Item in a Recyclerview to a fragment.
I currently have my fragment transaction in the onBindView method of the adapter.
public void onClick(View v) {
...
activity.getSupportFragmentMnager().beginTransaction()
.addSharedElement(v, "SharedString")
.replace(R.id.container, fragment2)
.addToBackStack(null)
.commit();
}
In the android docs, addSharedElement(view and string) confuse me. How do I give the view a unique ID and should I even be using v here?
Can the string be what ever I want?

here is my implementation. There is FragmentList with RecyclerView with images on each item. And there is FragmentDetail with only on big image. Image from FragmentList list item fly to FragmentDetail. TransitionName of animated view on FragmentList and FragmentDetail must be same. So I give unique transition name for each list item ImageView:
imageView.setTransitionName("anyString" + position)
Then I pass that string to FragmentDetail via setArguments and set big image transitionName to that string. Also we should provide Transition which describes how view from one view hierarchy animates to another viewhierarchy. After that we should pass that transition to fragment. I do it before FragmentTransaction:
detailFragment.setSharedElementEnterTransition(getTransition());
detailFragment.setSharedElementReturnTransition(getTransition());
Or you can override getSharedElementEnterTransition and getSharedElementReturnTransition of Fragment and declare transition there. Here is full code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, new FragmentList())
.commit();
}
}
public void showDetail(View view) {
String transitionName = view.getTransitionName();
FragmentDetail fragment = new FragmentDetail();
fragment.setArguments(FragmentDetail.getBundle(transitionName));
fragment.setSharedElementEnterTransition(getTransition());
fragment.setSharedElementReturnTransition(getTransition());
getSupportFragmentManager()
.beginTransaction()
.addSharedElement(view, transitionName)
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
}
private Transition getTransition() {
TransitionSet set = new TransitionSet();
set.setOrdering(TransitionSet.ORDERING_TOGETHER);
set.addTransition(new ChangeBounds());
set.addTransition(new ChangeImageTransform());
set.addTransition(new ChangeTransform());
return set;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
FragmentList:
public class FragmentList extends Fragment {
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_list, container, false);
RecyclerView rv = view.findViewById(R.id.recyclerview);
rv.setAdapter(new ListAdapter());
return view;
}
private class ListAdapter extends RecyclerView.Adapter {
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new Holder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Holder hold = (Holder) holder;
hold.itemView.setOnClickListener(v -> {
((MainActivity) getActivity()).showDetail(hold.imageView);
});
//unique string for each list item
hold.imageView.setTransitionName("anyString" + position);
}
#Override
public int getItemCount() {
return 10;
}
private class Holder extends ViewHolder {
ImageView imageView;
public Holder(View view) {
super(view);
imageView = view.findViewById(R.id.image);
}
}
}
}
fragment_list.xml
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
FragmentDetail:
public class FragmentDetail extends Fragment {
private static final String NAME_KEY = "key";
public static Bundle getBundle(String transitionName) {
Bundle args = new Bundle();
args.putString(NAME_KEY, transitionName);
return args;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_detail, container, false);
String transitionName = getArguments().getString(NAME_KEY);
ImageView imageView = view.findViewById(R.id.image);
imageView.setTransitionName(transitionName);
return view;
}
}
fragment_detail.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="#+id/image"
android:layout_width="300dp"
android:layout_height="300dp"
android:src="#drawable/cat"/>
</LinearLayout>
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/cat"/>
</LinearLayout>
Here is result:
TransitionName may be any string you want.
There is ViewCompat.setTransitionName if you need support pre Lollipop devices.

Adding to the ashakirov's answer:
Problem
Return Transition was not working!
Reason:
On popbackstack from Fragment B to Fragment A, Fragment A's onCreateView is called and if your data is still loading then the return transition won't work with only ashakirov's code.
Solution
Postpone the transition in your fragments
Add this line where the loading starts in your fragment A:
postponeEnterTransition();
After your data is loaded or you've set your adapter, write this:
startPostponedEnterTransition();
This ensures that your transition only happens after your data is loaded.
Also, make sure you start the transition even in 'data failed to load scenarios'.
If you want to postpone the transition in your fragment B when going from A to B then add this to your fragment B:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//hold the transition
postponeEnterTransition();
//when the views are available then start the transition
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
view.getViewTreeObserver().removeOnPreDrawListener(this);
startPostponedEnterTransition();
return true;
}
});
}

Related

Recyclerview not showing data untill i scroll up in a viewpager with two fragments

I have an Activity with a ViewPager which has two Fragments A and B
This two fragments inflate the same layout. that is they use the same xml layout.
xml shared by the two fragments
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/constraintLayout"
android:background="#color/md_white_1000"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/propRV"
android:scrollbars="vertical"
app:layout_constraintTop_toTopOf="#id/constraintLayout"
app:layout_constraintLeft_toLeftOf="#id/constraintLayout"
app:layout_constraintBottom_toBottomOf="#id/constraintLayout"
app:layout_constraintRight_toRightOf="#id/constraintLayout"
>
</android.support.v7.widget.RecyclerView>
//other views
</android.support.constraint.ConstraintLayout>
fragment A
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_items, container, false);
}
fragment B
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_items, container, false);
}
When I open the activity that contains my two fragments, items in Fragment A shows up well but when I scroll to Fragment B, items in Recyclerview at Fragment B do not show up until i try to scroll up my Recyclerview.
I have checked the adapter for Recyclerview at fragment B and saw that onBindViewHolder() is not being called until I scroll up. below is the adapter
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Object> properties;
private Context context;
public CustomAdapter(Context context,ArrayList<Object> properties){
this.properties = properties;
this.context = context;
}
public int getItemViewType(int position) {
Object coreDetails = properties.get(position);
if(coreDetails instanceof CoreDetails){
return 0;
}else{
return 1;
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == 0){
return new RHolder(LayoutInflater.from(context).inflate(R.layout.r_layout,parent,false));
}else{
return new SHolder(LayoutInflater.from(context).inflate(R.layout.s_layout,parent,false));
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return properties.size();
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
final Object object = properties.get(position);
//setting data
}
}
With that info, what is making items at Fragment B Recyclerview not to show up until I scroll up?
I was able to solve the problem by "refreshing the recyclerview"
recyclerview.swapAdapter(myAdapter,false);
recyclerview.setLayoutManager(myLayoutManager);
myAdapter.notifyDataSetChanged();

Layout for tablets using two fragments

I am doing a sample project as an excercise and want to display two fragments in the same activity when dealing with tablets(7' and 10').
So what I have so far is this.
As you can see I can display the data of my recyclerview in the left (static) fragment. However the right fragment is empty.
So I have two questions.
1) How to display by default in the right fragment the data of the first row of recyclerview?(ie image and article)
2) How to implement the click listener and update the right fragment?
Here is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private boolean mTwoPane;
private static final String DETAIL_FRAGMENT_TAG = "DFTAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.detailed_match_reports)!=null) {
mTwoPane = true;
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.detailed_match_reports, new DetailedActivityFragment(),DETAIL_FRAGMENT_TAG)
.commit();
}else{
mTwoPane = false;
}
}
}
}
layout/activity_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
tools:context="theo.testing.androidservices.activities.MainActivity"
tools:layout="#android:layout/list_content" />
layout-sw600dp/activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
tools:context="theo.testing.androidservices.activities.MainActivity">
<fragment
android:id="#+id/match_reports"
android:name="theo.testing.androidservices.fragments.MainActivityFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#android:layout/list_content" />
<FrameLayout
android:id="#+id/detailed_match_reports"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4" />
</LinearLayout>
MainActivityFragment
public class MainActivityFragment extends Fragment {
public static final String TAG = "AelApp";
public static ArrayList<MyModel> listItemsList;
RecyclerView myList;
public static MatchReportsAdapter adapter;
public MainActivityFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateMatchReport();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTitle("Match Report");
View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
listItemsList = new ArrayList<>();
myList = (RecyclerView)rootView.findViewById(R.id.listview_match_reports);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
myList.setHasFixedSize(true);
myList.setLayoutManager(linearLayoutManager);
adapter = new MatchReportsAdapter(getActivity(), listItemsList);
myList.setAdapter(adapter);
return rootView;
}
public void updateMatchReport(){
Intent i = new Intent(getActivity(), MatchReport.class);
getActivity().startService(i);
}
}
First let me answer the second question. To show a fragment on the right side of the screen add something like this (note how I'm using that id of the frame layout to replace the fragment):
Fragment fragment = new MyRightSideFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.detailed_match_reports, fragment).commit();
Now, for the first question, you need to implement click listener, you can find an example here.
public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
showDetail(position);
}
});
}
}
Notice that I'm using the tag of the view to identify the position (so somwhere in your onBindViewHolder code you must set this tag).
public function showDetail(int position) {
... show fragment por position
}
and finally, when your in your OnCreateView or somewhere in your setup code, call showDetail(0).

Open Fragment OnClick on Recyclerview item from ApI

I am getting data from API in recycleview using AQuery but now i want to open fragment from API onclick on recyclerview item so how can i implement this.
I want to do same as Instagram app,like on home page when we click on name we get all the details of users on another fragment.
//CouponFragment.java
public class CouponFragment extends Fragment implements CouponList.OnActionCompleted{
private RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
recyclerView = new RecyclerView(getActivity());
return recyclerView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> coupons = new ArrayList<>();
coupons.add("Tamil");
coupons.add("English");
coupons.add("Malay");
coupons.add("Chinese");
recyclerView.setAdapter(new CouponList(coupons,CouponFragment.this));
}
#Override
public void OnClick(Coupon coupon){
//new fragment
CouponDetails couponDetails = new CouponDetails();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.home_container, couponDetails);
//R.id.home_container is your FrameLayout id
transaction.addToBackStack("couponDetails");
transaction.commit();
}
}
cardview_coupon_info.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/tools"
android:foreground="?android:attr/selectableItemBackground"
android:transitionName="coupon_info_card"
android:id="#+id/coupon_info_card"
android:clickable="true"
android:layout_margin="#dimen/item_margin"
card_view:cardElevation="6dp"
card_view:cardCornerRadius="4dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/coupon_description"
android:gravity="start"
android:layout_margin="4dp" />
</android.support.v7.widget.CardView>
CouponList.java (Recyclerview adapter)
public class CouponList extends RecyclerView.Adapter<CouponList.ViewHolder> {
private ArrayList<String> coupons;
private OnActionCompleted callback;
public CouponList(ArrayList<String> coupons,OnActionCompleted callback)
{
this.coupons = coupons;
this.callback = callback;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_coupon_info,parent,false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.description.setText(coupons.get(position);
}
#Override
public int getItemCount() {
return coupons.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView description;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.coupon_description);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String coupon = coupons.get(getAdapterPosition());
callback.OnClick(coupon);
}
}
public interface OnActionCompleted {
public void OnClick(Coupon coupon);
}
}
You can use this in Activity as well for easy implementation for multiple widget clicks in recycler view item :)
Do the following in your recycler view item onClick.
FragmentManager fm = getFragmentManager();// If you're in an activity.
FragmentManager fm = getSupportFragmentManager();// If you're already inside another fragment
YourFragment yfObj = new YourFragment();
fm.beginTransaction().replace(R.id.fragmentContainer, yfObj).commit();
Here, fm is the FragmentManager object, with which only you can conduct a fragment transaction, such as loading a new fragment.
yfObj is the object of the fragment class that you want to load.
R.id.fragmentContainer is the id of the container layout you have declared in your XML file, where you want to load the fragment.
Hope this helps !

Android TabLayout ViewPager not inflating tab fragment on backstack

I've got a tab view set up that that has custom fragments for each tab using a viewpager. This is my code:
Holding Fragment
public class FragInboxMainView extends Fragment implements CGFragment {
private CGController controller;
private CGFragment thisFragment;
#Bind(R.id.inboxViewPager)ViewPager inboxViewPager;
#Bind(R.id.inboxTabs)TabLayout inboxTabLayout;
#Bind(R.id.inbox_progress_wheel)ProgressWheel inboxProgressWheel;
public FragInboxMainView(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_inbox_mainview, container, false);
ButterKnife.bind(this, rootView);
thisFragment = this;
Globals g = Globals.getInstance();
/** Show loading spinner */
this.inboxProgressWheel.setBarColor(ContextCompat.getColor(controller.getContext(), g.getUserObject().getUserThemeColor()));
this.inboxProgressWheel.setVisibility(View.VISIBLE);
/** Display the profile information based off the ID */
controller.displayInbox(thisFragment);
return rootView;
}
public void hideProgressSpinner() {
this.inboxProgressWheel.setVisibility(View.GONE);
}
public ViewPager getInboxViewPager() {
return this.inboxViewPager;
}
public TabLayout getInboxTabLayout() {
return this.inboxTabLayout;
}
}
Its layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:wheel="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/inboxTabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
<com.pnikosis.materialishprogress.ProgressWheel
android:id="#+id/inbox_progress_wheel"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
wheel:matProg_barColor="#5588FF"
wheel:matProg_progressIndeterminate="true"
android:visibility="gone"/>
<android.support.v4.view.ViewPager
android:id="#+id/inboxViewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
Tab fragment and its inflation file
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/main_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.baoyz.widget.PullRefreshLayout
android:id="#+id/tabPullRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/tabRecyclerHolder"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:clipToPadding="false"
android:layout_centerInParent="true"/>
</com.baoyz.widget.PullRefreshLayout>
<com.melnykov.fab.FloatingActionButton
android:id="#+id/tabFab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:src="#mipmap/ic_add_white"/>
</android.support.design.widget.CoordinatorLayout>
public class TabRecyclerHolder extends Fragment {
#Bind(R.id.tabRecyclerHolder) RecyclerView tabRecyclerHolder;
#Bind(R.id.tabPullRefresh) PullRefreshLayout tabPullRefresh;
#Bind(R.id.tabFab) FloatingActionButton recyclerFab;
private String tabTitle = "Title";
public TabRecyclerHolder(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_recycler_holder, container, false);
ButterKnife.bind(this, rootView);
recyclerFab.hide(false);
tabPullRefresh.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
return rootView;
}
public RecyclerView getTabRecyclerHolder() {
return this.tabRecyclerHolder;
}
public FloatingActionButton getRecyclerFab() {
return this.recyclerFab;
}
public String getTabTitle() {
return this.tabTitle;
}
public void setTabTitle(String title) {
this.tabTitle = title;
}
public PullRefreshLayout getTabPullRefresh() {
return this.tabPullRefresh;
}
}
My tab adapter
public class TabPagerAdapter extends FragmentStatePagerAdapter {
private CGController controller;
private List<Object> items;
public TabPagerAdapter(FragmentManager fm, CGController controller, List<Object> items) {
super(fm);
this.controller = controller;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Fragment getItem(int num) {
return (TabRecyclerHolder)items.get(num);
}
#Override
public String getPageTitle(int num){
return ((TabRecyclerHolder)items.get(num)).getTabTitle();
}
}
The processing code
public void viewInbox() {
/** Set up the views */
receivedHolder = new TabRecyclerHolder();
receivedHolder.setTabTitle(Constants.TAB_INBOX_RECEIVED);
sentHolder = new TabRecyclerHolder();
sentHolder.setTabTitle(Constants.TAB_INBOX_SENT);
tabs.add(receivedHolder);
tabs.add(sentHolder);
/** Set up the tabs */
final ViewPager inboxViewPager = inboxFragment.getInboxViewPager();
TabLayout inboxTabLayout = inboxFragment.getInboxTabLayout();
/** Set the adapter for the view pager */
inboxViewPager.setAdapter(new TabPagerAdapter(inboxFragment.getChildFragmentManager(), controller, tabs));
/** set up the tab look and feel */
inboxTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
inboxTabLayout.setTabMode(TabLayout.MODE_FIXED);
inboxViewPager.setOffscreenPageLimit(3);
inboxViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(inboxTabLayout));
inboxTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
inboxViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
/** And, display! */
inboxTabLayout.setupWithViewPager(inboxViewPager);
receivedAdapter = new RecyclerListAdapter(controller, items);
final RecyclerView receivedList = receivedHolder.getTabRecyclerHolder();
receivedList.setLayoutManager(new LinearLayoutManager(controller.getContext()));
receivedList.setAdapter(receivedAdapter);
}
There is some code i've missed out but its not pertanent to the question.
The code works perfectly when initially viewing the fragment. However since my application contains a single activity and just replaces a content view for each fragment navigated to, each fragment is added to the back stack and then popped when the back button is pressed. My issue is that when navigating back to this fragment the view inside the tab isn't being inflated, which means that no elements can be accessed (and therefore the app crashes while trying to display the data in the recyclerview etc).
I have had a look at this question: TabLayout ViewPager Not Loading When Using Backstack and implemented its suggestion (using getChildFragmentManager() when setting up the pager adapter) however that has not fixed my issue.
Help would be appreciated!
Change this public View onCreateView(LayoutInflater inflater,... to public void onViewCreated (View view, Bundle savedInstanceState)
so you are going to have something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_recycler_holder, container, false);
}
then
#Override
public void onViewCreated (View view, Bundle savedInstanceState){
ButterKnife.bind(this, view);
recyclerFab.hide(false);
tabPullRefresh.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
...
see if it helps
Extend FragmentStatePagerAdapter in TabPagerAdapter as
FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

Navigation drawer + ViewPager - fragments do not show

I have a problem with the layout I created. I used the Navigation Drawer as a main navigation pattern. It looks and works as I wanted, but the problem is that after returning to the fragment which holds ViewPager - the inner-fragments are not shown. However, they are shown when the application is first opened and shows the ViewPager-holding Fragment by default.
Other navigation drawer Fragments are displayed ok, so I don't expect that there is any problem with my Navigation Drawer implementation
RecordFragment.java (fragment holding ViewPager Fragments):
public class RecordFragment extends Fragment {
private ViewPager mViewPager;
public RecordFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.record_fragment, container, false);
//getActivity().setTitle(R.string.record);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewPager = (ViewPager) view.findViewById(R.id.record_pager);
FragmentManager manager = getFragmentManager();
mViewPager.setAdapter(new MyFragmentPagerAdapter(manager));
}
class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int item) {
Fragment fragment = null;
if (item == 0) {
fragment = new NumbersFragment();
} else if (item == 1) {
fragment = new MapFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String title = new String();
if (position == 0) {
title = "Numbers";
} else if (position == 1) {
title = "Map";
}
return title;
}
}
}
NumbersFragment.java (one of the Fragments holded by RecordFragment)
public class NumbersFragment extends Fragment {
public NumbersFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.numbers_fragment, container, false);
//getActivity().setTitle(R.string.record);
return rootView;
}
}
record_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/record_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
</LinearLayout>
You use Fragments inside another Fragment, in this case you need to use the Fragment#getChildFragmentManager() method:
FragmentManager manager = getChildFragmentManager();
If it doesn't work you can try to switch to FragmentStatePagerAdapter instead of FragmentPagerAdapter (but you still need to use child fragment manager).
As the ViewPager required Fragments and ViewPager itself on Fragment, we have to use getChildFragmentManager() instead of getSupportFragmentManager().

Categories

Resources