如何更新 ViewPager 中使用的片段数据?视图未显示更新的数据

How to update fragment#39;s data used in ViewPager? View is not showing the updated data(如何更新 ViewPager 中使用的片段数据?视图未显示更新的数据)
本文介绍了如何更新 ViewPager 中使用的片段数据?视图未显示更新的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道同一个问题已被问过很多次,但我无法解决我的问题.

I know the same question has been asked so many times but I am not able to solve my issue.

我创建了一个 Activity,它有一个 ViewPager,应该有 4 个 Pages.

I have created an Activity which has a ViewPager which should have 4 Pages.

我对所有页面使用相同的 Fragment.Fragment 有一个 GridView ,每当我滑动到另一个页面时都应该更新它.

I am using the same Fragment for all pages. The Fragment has a GridView which should be updated whenever I swipe to the other page.

以下是类 &我用来创建它的 XML 布局.

Following are the classes & XML layouts I have used to create it.

活动布局activity_discover.xml

 <android.support.v4.view.ViewPager
            android:id="@+id/activity_discover_view_pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip" >

            <android.support.v4.view.PagerTabStrip
                android:id="@+id/activity_discover_pager_tab_strip"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:textColor="@color/black"
                android:textSize="@dimen/header_text" />
        </android.support.v4.view.ViewPager>
</RelativeLayout>

活动DiscoverActivity.java

public class DiscoverActivity extends FragmentActivity implements OnClickListener, OnPageChangeListener
{
    private final static String TAG = "DiscoverActivity";
    private UtilDialog utilDialog;

    MPagerAdapter adapterViewPager;
    PagerTabStrip pagerTabStrip;
    ViewPager viewPager;

    public ArrayList<String> listCategory;


    LMProgressDialog progressDialog;
    private RelativeLayout relativeCountry;
    private RelativeLayout relativeCity;
    private TextView tvCountry;
    private TextView tvCity;

    private String selectedCategory;
    private int selectedCityID = 0;
    private int selectedCategoryID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discover);
        initParameters();
        initView();
    }

    void initParameters()
    {
        progressDialog = new LMProgressDialog(this);

        utilDialog = new UtilDialog(this);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
        editor.commit();
        selectedCategory = getResources().getString(R.string.adventure);

        listCategory = new ArrayList<String>();
        listCategory.add(getResources().getString(R.string.adventure));
        listCategory.add(getResources().getString(R.string.night_life));
        listCategory.add(getResources().getString(R.string.life_styles));
        listCategory.add(getResources().getString(R.string.events));
    }

    void initView()
    {

        viewPager = (ViewPager) findViewById(R.id.activity_discover_view_pager);
        viewPager.setOnPageChangeListener(this);
        adapterViewPager = new MPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapterViewPager);

        pagerTabStrip = (PagerTabStrip) findViewById(R.id.activity_discover_pager_tab_strip);
        pagerTabStrip.setTabIndicatorColor(getResources().getColor(R.color.white));

                }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    public class MPagerAdapter extends FragmentPagerAdapter
    {
        private Map<Integer, String> mFragmentTags;
        private FragmentManager mFragmentManager;

        public MPagerAdapter(FragmentManager fm)
        {
            super(fm);
            mFragmentManager = fm;
            mFragmentTags = new HashMap<Integer, String>();
        }

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

        @Override
        public Fragment getItem(int position)
        {
             Fragment fragment = Fragment.instantiate(DiscoverActivity.this,
             FragmentMediaContent.class.getName(), null);

            return fragment;
        }

        @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);
            }
            return obj;
        }

        public Fragment getFragment(int position)
        {
            String tag = mFragmentTags.get(position);
            if (tag == null)
                return null;
            return mFragmentManager.findFragmentByTag(tag);
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return listCategory.get(position).toString().toUpperCase();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0)
    {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2)
    {

    }

    @Override
    public void onPageSelected(int position)
    {
        selectedCategoryID = position;
        selectedCategory = listCategory.get(position);
        try
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Constants.CITY_ID, selectedCityID);
            jsonObject.put(Constants.CATEGORY, selectedCategory);
            makeJsonObjectRequest(Request.Method.POST, jsonObject, API.URL_LOAD_MEDIA);
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    void prepareMediaList(JSONArray arrayMedia)
    {
        int noOfMedia = arrayMedia.length();

        ArrayList<MediaType> listMedia = new ArrayList<MediaType>();
        for (int i = 0; i < noOfMedia; i++)
        {
            try
            {
                JSONObject objectMedia = arrayMedia.getJSONObject(i);
                int id = objectMedia.getInt(Constants.ID);
                String category = objectMedia.getString(Constants.CATEGORY);
                String mediaType = objectMedia.getString(Constants.MEDIA_TYPE);
                int cityID = objectMedia.getInt(Constants.CITIES_ID);
                String path = objectMedia.getString(Constants.PATH);
                String thumbnailPath = objectMedia.getString(Constants.THUMBNAIL_PATH);
                String description = objectMedia.getString(Constants.DESCRIPTION);
                int userID = objectMedia.getInt(Constants.USERS_ID);

                listMedia.add(new MediaType(id, mediaType, path, category, userID, cityID, 0, description, thumbnailPath));
            } catch (JSONException e)
            {
                e.printStackTrace();
            }
        }

        FragmentMediaContent fragment = (FragmentMediaContent) adapterViewPager.getFragment(selectedCategoryID);
        Log.i(TAG, "fragment: " + fragment);
        fragment.updateData(listMedia, selectedCategory);
    }
}

FragmentFragmentMediaContent.java:

public class FragmentMediaContent extends Fragment
{
    private final static String TAG = "FragmentMediaContent";
    public static final String FRAGMENT_POSITION = null;

    private GridView gridView;
    private UtilDialog utilDialog;
    private SharedPreferences preferences;
    private Editor editor;

    private ArrayList<MediaType> listMedia;
    MediaAdapter mediaAdapter;

    private int cityID;
    private String category;

    LMProgressDialog progressDialog;
    TextView tvTest;

     public static FragmentMediaContent newInstance(int num)
     {
         FragmentMediaContent f = new FragmentMediaContent();
         return f;
     }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment_media_content, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        initParameters();
        initViews();
    }

    void initParameters()
    {
        getSize();
        listMedia = new ArrayList<MediaType>();
        utilDialog = new UtilDialog(getActivity());
        progressDialog = new LMProgressDialog(getActivity());
        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        editor = preferences.edit();
        mediaAdapter = new MediaAdapter(getActivity(), listMedia);
    }

    void initViews()
    {
        tvTest = (TextView) getActivity().findViewById(R.id.fragment_media_content_tv_test);
        tvTest.setText(category+" no of media");
        tvTest.setVisibility(View.GONE);
        gridView = (GridView) getActivity().findViewById(R.id.fragment_media_content_grid_view);
        gridView.setAdapter(mediaAdapter);

    }


    /**
     * MediaAdapter : ArrayAdapter class which prepares view for list of
     * MediaType.
     * 
     */
    class MediaAdapter extends ArrayAdapter<MediaType>
    {
        MediaAdapter(Context context, ArrayList<MediaType> list)
        {
            super(context, R.layout.cell_media_view, R.id.cell_media_view_tv_test, list);
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            View row = super.getView(position, convertView, parent);
            MediaViewHolder holder = (MediaViewHolder) row.getTag();
            if (holder == null)
            {
                holder = new MediaViewHolder(row);
                row.setTag(holder);
            }

            final MediaType mediaType = getMedia(position, this);
            String thumbnailPath = mediaType.getThumbnailPath();
            String path = mediaType.getPath();
            String type = mediaType.getMediaType();

            // imageLoader.get(type.equals(Constants.TYPE_IMAGE) ? path :
            // thumbnailPath, ImageLoader.getImageListener(holder.ivMedia,
            // R.drawable.logo, R.drawable.ic_launcher));

            holder.ivType.setVisibility(type.equals(Constants.TYPE_IMAGE) ? View.GONE : View.VISIBLE);

            holder.ivMedia.setLayoutParams(new FrameLayout.LayoutParams(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
            Picasso.with(getActivity()).load(type.equals(Constants.TYPE_IMAGE) ? path : thumbnailPath).noFade().centerCrop().resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE).placeholder(R.drawable.loading)
                    .error(R.drawable.no_image).into(holder.ivMedia);

            return row;
        }
    }

    public void updateData(ArrayList<MediaType> listMedia, String category)
    {
        Log.i(TAG, "Updating data for: " + category);
        Log.i(TAG, "No of media items: " + listMedia.size());
        // this.listMedia.clear();
        // this.listMedia.addAll(listMedia);
        // mediaAdapter.notifyDataSetChanged();

        mediaAdapter = new MediaAdapter(getActivity(), listMedia);
        gridView.setAdapter(mediaAdapter);
        tvTest.setText(category + ", No of Media : " + listMedia.size());
    }

    int THUMBNAIL_SIZE = 200;

    /**
     * @param position
     * @return MediaType object from specified position
     */
    private MediaType getMedia(int position, MediaAdapter mediaAdapter)
    {
        return (MediaType) mediaAdapter.getItem(position);
    }
}

片段 fragment_media_content.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/fragment_media_content_tv_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/white" />

    <GridView
        android:id="@+id/fragment_media_content_grid_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="5dip"
        android:numColumns="3"
        android:verticalSpacing="5dip" />

</LinearLayout>

在页面滑动时(或者它可能是任何其他事件),我点击了一个 API,它为我提供了一些我必须在相应的 Fragment 中更新的数据.

On page swipe (or it could be any other event) I hit an API which gives me some data that I have to update in the corresponding Fragment.

每当我从服务器获取数据时,我都会调用 prepareMediaList 方法,该方法调用 FragmentupdateData 方法.我可以在日志中看到列表中有数据,但该数据未显示在 FragmentGridView 中(甚至在 TextView 中也不显示).

Whenever I get the data from server I call the prepareMediaList method which calls the updateData method of Fragment. I can see in logs that there is data in list but that data is not shown in the Fragment's GridView (not even in TextView).

我真的不明白这有什么问题.

I am really not getting what is wrong in this.

现在变得很郁闷,看起来很简单却还是找不到解决办法.

Now it has become very frustrating, looks so simple but still couldn't find any solution.

编辑我只尝试了一个 Fragment &它工作正常.所以有些东西与倍数有关.

Edit I just tried with one Fragment only & it is working properly. So there is something which has to do with multiples.

编辑 2

我找不到解决方案,所以我不得不切换到其他方式.我从 ViewPager 中删除了 Fragment,而是向其中添加了静态视图.在我的例子中,我向 ViewPager 添加了四个 GridView.这很简单有点复杂,但最重要的是,它按照我想要的方式工作.

I couldn't find the solution for this so I had to switch to alternate way. I removed the Fragments from ViewPager instead I added static views to it. In my case I added four GridViews to ViewPager. This was simple & bit complex but most important thing is, it is working the way I wanted.

但我仍在寻找答案.

推荐答案

在详细检查了您的代码后,我发现您不需要在 updateData 方法中重新初始化 MediaAdapter.

After checking your code more in details i see you do not require to re-initliaze your MediaAdapter inside updateData method.

您只需将 updateData 更新为

listMedia.clear();
this.listMedia.addAll(listMedia);
mediaAdapter.notifyDatasetChanged();

这将在 gridview 中重新加载您的数据.我建议的更改将刷新用于呈现 gridview 的数组列表中的数据,然后通知您的 mediaAdapter 重新加载列表.

This will reload your data in gridview. Change i suggested will refresh the data in your arraylist which is being used for rendering gridview and then you notify your mediaAdapter to reload the list.

这篇关于如何更新 ViewPager 中使用的片段数据?视图未显示更新的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)