SwipeRefreshLayout + ViewPager,片段不起作用

时间:2018-02-02 04:43:30

标签: android android-fragments android-recyclerview android-tablayout swiperefreshlayout

我在许多页面中实现了SwipeRefreshLayout,它运行正常。但是在这里我遇到了一个特定的实现,其中我有一个用于ViewPager的SwipeRefreshLayout和一个持有FragmentPagerAdapter的ViewPager。

就我而言,我有一个带有两个标签的ViewPager,每个标签都使用RecyclerView保存片段。在主页面上我有一个SwipeRefreshLayout,在onRefresh上我需要加载API并在ViewPager中更新片段。更新工作正常,但遗憾的是Fragment(ViewPager选项卡Item)中的RecyclerView没有滚动顶部,它总是调用SwipeToRefresh。

我熟悉将SwipeRefreshLayout与RecyclerView一起使用,但问题是SwipeRefreshLayout的主要子项是ViewPager,它内部有Fragment,而该片段正在持有RecyclerView。

我想到了在RecyclerView的片段中移动Swip​​eRefreshLayout,但在这里我还有一些挑战,比如Fragments都有相同的API。这样我就可以直接在ViewPager上使用SwipeRefreshLayout来刷新我的数据。

以下是我的一些代码。

MainContacts.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ll_no_records"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ImageView
            android:id="@+id/iv_retry"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"

            android:contentDescription="@string/todo"
            android:src="@drawable/ic_reload" />

        <TextView
            android:id="@+id/textError"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:gravity="center"
            android:text="@string/no_contact_found"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorDarkGray" />


    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_process"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:alpha="1"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="visible">


        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="50dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:indeterminate="true" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/fetching"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorDarkGray" />
    </LinearLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/contacts_screen"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <android.support.design.widget.TabLayout
                android:id="@+id/my_contacts_tabs"
                style="@style/MyCustomTabLayout"
                android:layout_width="match_parent"
                app:tabBackground="@color/colorWhite"
                android:layout_height="wrap_content" />

            <android.support.v4.view.ViewPager
                android:id="@+id/my_contacts_view_pager"
                android:layout_width="match_parent"
                android:layout_height="0px"
                android:layout_weight="1"
                android:background="@android:color/transparent" >
            </android.support.v4.view.ViewPager>
        </LinearLayout>

    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>

contacts.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hc="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/ll_no_records"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:orientation="vertical"
    android:visibility="gone">

    <ImageView
        android:id="@+id/iv_retry"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:contentDescription="@string/todo"
        android:src="@drawable/ic_reload" />

    <TextView
        android:id="@+id/textError"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:gravity="center"
        android:text="@string/no_contact_found"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        android:textColor="@color/colorDarkGray" />


</LinearLayout>

<com.diegocarloslima.fgelv.lib.FloatingGroupExpandableListView
    android:id="@+id/contactList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/searchContainer"
    android:animateLayoutChanges="true"
    android:childDivider="@android:color/transparent" />

</RelativeLayout>

MainFragment(我用来加载子片段,SwipeTORefreshLayout + ViewPager)

public class MainFragment extends BaseFragment {

    private TextView mTextError;

    private LinearLayout llNoRecords, ll_process;
    private ImageView iv_retry;
    private MaterialSearchView materialSearchView;
    PHCJsonResponseContactDetailModel mContactResponseModel;
    int expandableListSelectionType = ExpandableListView.PACKED_POSITION_TYPE_NULL;
    boolean actionModeEnabled;
    private Activity mActivity;

    SwipeRefreshLayout mSwipeRefreshLayout;
    private ViewPager viewPager;
    TabLayout tabLayout;
    ContactsTabPagerAdapter mAdapter;

    ArrayList<PHCContactDetailModel> mContactList =new ArrayList<>();
    ArrayList<PHCContactDetailModel> mFavoriteList;

    boolean isSwipeToRefresh;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mActivity = getActivity();
        View view = inflater.inflate(R.layout.phc_contact_fragment, container, false);

        getViewId(view);
        setListener();
        if (isNetworkAvailable()) {
            if(((MainDrawerActivity)mActivity).getPHCContactFragmentData()==null)
            getAllContactData();
            else
                updateWidgets();
        } else {
            showNoNetworkToast();
            llNoRecords.setVisibility(View.VISIBLE);
            mTextError.setText(getResources().getText(R.string.no_internet_retry));
        }
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);


    }

    @Override
    public void onResume() {
        super.onResume();

    }

    /*@Override
    public void onPrepareOptionsMenu(final Menu menu) {
        getActivity().getMenuInflater().inflate(R.menu.menu_fragment_group, menu);

    }*/

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        inflater.inflate(R.menu.menu_fragment_contacts, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        materialSearchView.setMenuItem(item);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_create_group) {
            Intent createGroupIntent = new Intent(getActivity(), PHCCreateGroupActivity.class);
            createGroupIntent.putExtra("comeFrom", PHCAppConstant.GROUP_ADD);
            getActivity().startActivity(createGroupIntent);
        }
        return super.onOptionsItemSelected(item);
    }

    private void setListener() {
        iv_retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNetworkAvailable()) {
                    getAllContactData();
                } else {
                    showNoNetworkToast();
                }
            }
        });

    }

    private void getViewId(View view) {

        mTextError = (TextView) view.findViewById(R.id.textError);
        ll_process = (LinearLayout) view.findViewById(R.id.ll_process);

        llNoRecords = (LinearLayout) view.findViewById(R.id.ll_no_records);
        iv_retry = (ImageView) view.findViewById(R.id.iv_retry);

        viewPager = (ViewPager) view.findViewById(R.id.my_contacts_view_pager);
        tabLayout = (TabLayout) view.findViewById(R.id.my_contacts_tabs);

        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);

        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
                android.R.color.holo_green_dark,
                android.R.color.holo_orange_dark,
                android.R.color.holo_blue_dark);


        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if(mContactResponseModel!=null && mContactResponseModel.getData().size() >0)
                {
                    isSwipeToRefresh = true;
                    getAllContactData();
                }
            }
        });


        materialSearchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);

    }

    private void getAllContactData() {
        if (isNetworkAvailable()) {
//            showProgress();
            PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
            Call<PHCJsonResponseContactDetailModel> call = apiService.contactData(getApplicationData(getActivity()).getAuthToken(), getApplicationData(getActivity()).getUserID());
            call.enqueue(new Callback<PHCJsonResponseContactDetailModel>() {
                @Override
                public void onResponse(Call<PHCJsonResponseContactDetailModel> call, Response<PHCJsonResponseContactDetailModel> response) {
                    Log.d(TAG, "getContacts URL " + response.raw().request().url());
                    Log.d(TAG, "getContacts Resp " + new Gson().toJson(response.body()));
                    mContactResponseModel = response.body();
                    ((MainDrawerActivity)mActivity).setPHCContactFragmentData(mContactResponseModel);

                    if(mSwipeRefreshLayout.isRefreshing())
                    {
                        // cancel the Visual indication of a refresh
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                    if(isSwipeToRefresh)
                    {
                            isSwipeToRefresh=false;
                            updateWidgets();
                    }
                    else
                    updateWidgets();
                }

                @Override
                public void onFailure(Call<PHCJsonResponseContactDetailModel> call, Throwable t) {

                    if(mSwipeRefreshLayout.isRefreshing())
                    {
                        // cancel the Visual indication of a refresh
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                    isSwipeToRefresh=false;
                    dismissProgress();
                    mTextError.setVisibility(View.VISIBLE);
                }
            });
        } else {

            isSwipeToRefresh=false;

            if(mSwipeRefreshLayout.isRefreshing())
            {
                // cancel the Visual indication of a refresh
                mSwipeRefreshLayout.setRefreshing(false);
            }

            showNoNetworkAlert();
        }
    }

    private void updateWidgets() {

        if (mContactResponseModel.getStatusCode() == 401 || mContactResponseModel.getStatusCode() == 402) {
            showSessionExpireAlert(mContactResponseModel.getStatusMessage(), mContactResponseModel.getStatusCode());
            return;
        }
        if (mContactResponseModel != null && mContactResponseModel.getStatusCode() == 1) {
            dismissProgress();
            mTextError.setVisibility(View.GONE);

            mContactList = mContactResponseModel.getData();
            mFavoriteList = mContactResponseModel.getData();

            if(mContactList!=null && mContactList.size()>0)
            {
                llNoRecords.setVisibility(View.GONE);
                mAdapter = new ContactsTabPagerAdapter(getActivity().getApplicationContext(), getChildFragmentManager(), mContactList , mFavoriteList);

                viewPager.setAdapter(mAdapter);
                tabLayout.setupWithViewPager(viewPager);
            }
            else {
                llNoRecords.setVisibility(View.VISIBLE);
            }

        } else {
            dismissProgress();
            mTextError.setVisibility(View.VISIBLE);
        }
    }


    public void dismissProgress() {
        ll_process.setVisibility(View.GONE);
        super.dismissProgress();
    }


    private void initiateContactChat(final PHCFacilityDetailsModel facilityDetailsModel, final int groupPosition, final int childPosition) {
        String header = getApplicationData(getActivity()).getAuthToken();
        PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
        Call<PHCContactInitiateChatResponseModel> call = apiService.initiateContactChat(header, facilityDetailsModel.getUserId(), getApplicationData(getActivity()).getUserID(), 0);
        call.enqueue(new Callback<PHCContactInitiateChatResponseModel>() {
            @Override
            public void onResponse(Call<PHCContactInitiateChatResponseModel> call, Response<PHCContactInitiateChatResponseModel> response) {
                Log.d(TAG, "initiateContactChat URL " + response.raw().request().url());
                Log.d(TAG, "initiateContactChat Resp " + new Gson().toJson(response.body()));
                PHCContactInitiateChatResponseModel mContactInitiateChatModel = response.body();
                if (mContactInitiateChatModel != null && mContactInitiateChatModel.getStatusCode() == 1) {
                    Intent chatIntent = new Intent(getActivity(), PHCChatActivity.class);
//                    chatIntent.putExtra("headerName",mData.get(groupPosition).getFacilityDetails().get(childPosition).getUserName());
                    chatIntent.putExtra("headerName", facilityDetailsModel.getUserName());
                    chatIntent.putExtra("groupId", mContactInitiateChatModel.getData().getGroupId());
                    getActivity().startActivity(chatIntent);
                }
            }

            @Override
            public void onFailure(Call<PHCContactInitiateChatResponseModel> call, Throwable t) {
                Toast.makeText(getActivity(), "Something went wrong! Please try again", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

ContactsTabPagerAdapter.java

public class ContactsTabPagerAdapter extends FragmentPagerAdapter {

    /**
     * The Page count.
     */
    final int PAGE_COUNT = 2;

    private String[] tabTitles = { "Contacts", "Favorites" };

    private ArrayList<PHCContactDetailModel> mContactsList;
    private ArrayList<PHCContactDetailModel> mFavoritesList;

    Context mContext ;

    public ContactsTabPagerAdapter(Context context, FragmentManager fm ,ArrayList<PHCContactDetailModel> contacts , ArrayList<PHCContactDetailModel> favs) {
        super(fm);
        this.mContext = context;
        this.mContactsList = contacts;
        this.mFavoritesList=favs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {

            case 0:

                ContactsFragment mContactsFragment =new ContactsFragment();
                Bundle bundle=new Bundle();
                bundle.putSerializable("Contacts", (Serializable) mContactsList);

                mContactsFragment.setArguments(bundle);

                return mContactsFragment;

            case 1:

                FavoritesFragment mFavoritesFragment=new FavoritesFragment();

                Bundle pastBundle=new Bundle();
                pastBundle.putSerializable("Favorites", (Serializable) mFavoritesList);

                mFavoritesFragment.setArguments(pastBundle);

                return mFavoritesFragment;
        }

        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles[position];
    }

    /**
     * Update.
     *
     * @param lContactsList  contact list to update
     * @param lFavoritesList  favorites list to update
     */
//call this method to update fragments in ViewPager dynamically
    public void update(ArrayList<PHCContactDetailModel> lContactsList, ArrayList<PHCContactDetailModel> lFavoritesList) {

        this.mContactsList = lContactsList;
        this.mFavoritesList = lFavoritesList;

        notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof UpdatableFragment) {
            ((UpdatableFragment) object).update(mContactsList, mFavoritesList);
        }
        //don't return POSITION_NONE, avoid fragment recreation.
        return super.getItemPosition(object);
    }
}

ContactsFragment.java

public class ContactsFragment extends BaseFragment implements UpdatableFragment{

    private static final String TAG = "ContactFragmentTab";
    private FloatingGroupExpandableListView mContactExpandableList;
    private PHCContactAdapter mAdapter;
    WrapperExpandableListAdapter wrapperAdapter;
    boolean actionModeEnabled;
    private LinearLayout llNoRecords;
    private ArrayList<PHCContactDetailModel> mContactsData;

    public ContactsFragment() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);


    }

    @SuppressWarnings("unchecked")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);

        getViewId(rootView);

        Bundle bundle= getArguments();

        if(bundle !=null)
        {
            Log.d(TAG, "bundle is not empty");

            mContactsData= (ArrayList<PHCContactDetailModel>) bundle.getSerializable("Contacts");
        }
        System.out.print("Contacts Size::" + mContactsData.size());

        if(mContactsData!=null)
        {
            updateWidgets();
        }

        return rootView;
    }

    private void updateWidgets() {

        mAdapter = new PHCContactAdapter(getActivity(), mContactsData, new ListShowingHidingListener() {
            @Override
            public void listHideAndShow(boolean isData) {
                if (isData) {
                    llNoRecords.setVisibility(View.GONE);
                    mContactExpandableList.setVisibility(View.VISIBLE);
                    listUpdate();
                } else {
                    llNoRecords.setVisibility(View.VISIBLE);
                    mContactExpandableList.setVisibility(View.GONE);
                }
            }
        });

        wrapperAdapter = new WrapperExpandableListAdapter(mAdapter);

        mContactExpandableList.setAdapter(wrapperAdapter);
        try {
            for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
                mContactExpandableList.expandGroup(i);
            }
        } catch (Exception e) {
            Log.e("Exception in Expand", "" + e);
        }

    }

    private void listUpdate() {
        try {
            for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
                mContactExpandableList.expandGroup(i);
            }
        } catch (Exception e) {
            Log.e("Exception in Expand", "" + e);
        }
    }

    private void getViewId(View view) {
        //   mContactExpandableList = (ExpandableListView) view.findViewById(R.id.contactList);
        mContactExpandableList = (FloatingGroupExpandableListView) view.findViewById(R.id.contactList);



    }


    @Override
    public void update(ArrayList<PHCContactDetailModel> contactsData, ArrayList<PHCContactDetailModel> favoritesData) {

        this.mContactsData = contactsData;
        updateWidgets();
    }
}

同样我也有收藏夹示例。大多数情况下两者看起来都一样,这就是为什么不在这里发布。

很抱歉发布了很长的问题。对此有任何帮助。为我可怜的英语道歉。在此先感谢。

0 个答案:

没有答案