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

时间:2015-05-18 12:41:34

标签: android android-fragments android-viewpager

我知道同样的问题被问了很多次,但我无法解决我的问题。

我创建的Activity ViewPager应该有4 Pages

我对所有网页使用相同的FragmentFragment有一个GridView,只要我滑到另一个页面,就应该更新activity_discover.xml

以下是课程&我用来创建它的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); } }

Fragment

FragmentMediaContent.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

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>

Fragment

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

每当我从服务器获取数据时,我都会调用调用updateData Fragment方法的Fragment方法。我可以在日志中看到列表中有数据但该数据未显示在GridView的{​​{1}}中(甚至不在TextView中)。

我真的没有弄到这个错误。

现在它变得非常令人沮丧,看起来很简单,但仍然找不到任何解决方案。

修改 我刚试过只有一个Fragment&amp;它运作正常。所以有些东西与倍数有关。

修改2

我无法找到解决方案,因此我不得不切换到替代方式。我从Fragment中移除了ViewPager,而是向其添加了静态视图。在我的情况下,我向GridView添加了四个ViewPager。这很简单&amp;有点复杂,但最重要的是,它按照我想要的方式工作。

但我仍在寻找答案。

1 个答案:

答案 0 :(得分:0)

在详细检查您的代码后,我发现您不需要在updateData方法中重新启动MediaAdapter。

您只需要将updateData更新为

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

这将在gridview中重新加载您的数据。我建议的更改将刷新用于渲染gridview的arraylist中的数据,然后通知mediaAdapter重新加载列表。