List没有在片段viewpager android中更新

时间:2016-12-01 19:47:43

标签: java android

我有一项活动,在该活动中,我有一个持有四个片段的viewpager。在每个片段中都有一个自定义列表视图,当我尝试更新列表并执行notifyDataSetChanged()时,它不会更改或更新屏幕上的列表。下次它操纵下一个列表成员。任何帮助人员如何解决它。 这是我的片段类,我尝试在onpostdelete方法中更新列表

public class StreamFragment extends Fragment implements Constants,SwipeRefreshLayout.OnRefreshListener,ItemInterface {

private static final String STATE_LIST = "State Adapter Data";

private static final int PROFILE_NEW_POST = 4;

Spinner mNavSpinner;

ListView mListView;
TextView mMessage;
ImageView mSplash;

SwipeRefreshLayout mItemsContainer;

FloatingActionButton mFabButton;

private ArrayList<Item> itemsList;
private StreamListAdapter itemsAdapter;
private String uniID;
private int category = 0;
private int itemId = 0;
private int arrayLength = 0;
private Boolean loadingMore = false;
private Boolean viewMore = false;
private Boolean restore = false;

public StreamFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {

        itemsList = savedInstanceState.getParcelableArrayList(STATE_LIST);
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList, this);

        restore = savedInstanceState.getBoolean("restore");
        itemId = savedInstanceState.getInt("itemId");
        category = savedInstanceState.getInt("category");

    } else {

        itemsList = new ArrayList<Item>();
        itemsAdapter = new StreamListAdapter(getActivity(), itemsList, this);

        restore = false;
        itemId = 0;
        category = 0;
    }

    Bundle bundle = this.getArguments();
    if(bundle!=null)
    category = bundle.getInt("category", 0);
}

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

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

    mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
    mItemsContainer.setOnRefreshListener(this);

    mMessage = (TextView) rootView.findViewById(R.id.message);
    mSplash = (ImageView) rootView.findViewById(R.id.splash);

    mFabButton = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
    mFabButton.setImageResource(R.drawable.ic_action_new);

    mListView = (ListView) rootView.findViewById(R.id.listView);
    SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
    String uniname=preferences.getString("Uni","");
    uniID = preferences.getString("UniID","");
    mFabButton.attachToListView(mListView, new ScrollDirectionListener() {

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onScrollUp() {

        }

    }, new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            int lastInScreen = firstVisibleItem + visibleItemCount;

            if ((lastInScreen == totalItemCount) && !(loadingMore) && (viewMore) && !(mItemsContainer.isRefreshing())) {

                if (App.getInstance().isConnected()) {

                    loadingMore = true;

                    getItems();
                }
            }
        }
    });

    mListView.setAdapter(itemsAdapter);

    mFabButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getActivity(), NewItemActivity.class);
            startActivityForResult(intent, STREAM_NEW_POST);
        }
    });

    if (itemsAdapter.getCount() == 0) {

        showMessage(getText(R.string.label_empty_list).toString());

    } else {

        hideMessage();
    }

    if (!restore) {

        showMessage(getText(R.string.msg_loading_2).toString());

        getItems();
    }

    return rootView;
}

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    outState.putBoolean("restore", true);
    outState.putInt("itemId", itemId);
    outState.putInt("category", category);
    outState.putParcelableArrayList(STATE_LIST, itemsList);
}

@Override
public void onRefresh() {

    if (App.getInstance().isConnected()) {

        itemId = 0;
        getItems();

    } else {

        mItemsContainer.setRefreshing(false);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == STREAM_NEW_POST && resultCode == getActivity().RESULT_OK && null != data) {

        itemId = 0;
        getItems();
    }
}

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

    super.onCreateOptionsMenu(menu, inflater);
}

public void getItems() {

    mItemsContainer.setRefreshing(true);

    CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_STREAM_GET, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    if (!loadingMore) {

                        itemsList.clear();
                    }

                    try {

                        arrayLength = 0;

                        if (!response.getBoolean("error")) {

                            itemId = response.getInt("itemId");

                            if (response.has("items")) {

                                JSONArray itemsArray = response.getJSONArray("items");

                                arrayLength = itemsArray.length();

                                if (arrayLength > 0) {

                                    for (int i = 0; i < itemsArray.length(); i++) {

                                        JSONObject itemObj = (JSONObject) itemsArray.get(i);

                                        Item item = new Item(itemObj);

                                        itemsList.add(item);
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {

                        e.printStackTrace();

                    } finally {

                        loadingComplete();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            loadingComplete();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("accountId", Long.toString(App.getInstance().getId()));
            params.put("accessToken", App.getInstance().getAccessToken());
            params.put("itemId", Integer.toString(itemId));
            params.put("clientId", CLIENT_ID);
            //params.put("category", Integer.toString(category));
            params.put("universityId",uniID );
            // params.put("category", uniID);
            params.put("language", "en");

            return params;

        }
    };

    App.getInstance().addToRequestQueue(jsonReq);
}

public void loadingComplete() {

    if (arrayLength == LIST_ITEMS) {

        viewMore = true;

    } else {

        viewMore = false;
    }

    itemsAdapter.notifyDataSetChanged();

    if (itemsAdapter.getCount() == 0) {

        if (StreamFragment.this.isVisible()) {

            showMessage(getText(R.string.label_empty_list).toString());
        }

    } else {

        hideMessage();
    }

    loadingMore = false;
    mItemsContainer.setRefreshing(false);
}

public void onCategoryChange(int cat) {

    itemId = 0;

    getItems();

    category = cat;
}

public void report(int position) {

    android.app.FragmentManager fm = getActivity().getFragmentManager();

    PostReportDialog alert = new PostReportDialog();

    Bundle b  = new Bundle();
    b.putInt("position", position);
    b.putInt("reason", 0);

    alert.setArguments(b);
    alert.show(fm, "alert_dialog_post_report");
}

public void onPostReport(int position, int reasonId) {

    final Item item = itemsList.get(position);

    if (App.getInstance().isConnected()) {

        Api api = new Api(getActivity());

        api.postReport(item.getId(), reasonId);

    } else {

        Toast.makeText(getActivity(), getText(R.string.msg_network_error), Toast.LENGTH_SHORT).show();
    }
}

public void remove(int position) {

    android.app.FragmentManager fm = getActivity().getFragmentManager();

    PostDeleteDialog alert = new PostDeleteDialog();

    Bundle b  = new Bundle();
    b.putInt("position", position);

    alert.setArguments(b);
    alert.show(fm, "alert_dialog_post_delete");
}

public void onPostDelete(int position) {

    final Item item = itemsList.get(position);

    itemsList.remove(position);
    itemsAdapter.notifyDataSetChanged();

    if (mListView.getAdapter().getCount() == 0) {

        showMessage(getText(R.string.label_empty_list).toString());

    } else {

        hideMessage();
    }

    if (App.getInstance().isConnected()) {

        Api api = new Api(getActivity());

        api.postDelete(item.getId());

    } else {

        Toast.makeText(getActivity(), getText(R.string.msg_network_error), Toast.LENGTH_SHORT).show();
    }
}

public void onPostRemove(final int position) {

    /** Getting the fragment manager */
    android.app.FragmentManager fm = getActivity().getFragmentManager();

    /** Instantiating the DialogFragment class */
    PostDeleteDialog alert = new PostDeleteDialog();

    /** Creating a bundle object to store the selected item's index */
    Bundle b  = new Bundle();

    /** Storing the selected item's index in the bundle object */
    b.putInt("position", position);

    /** Setting the bundle object to the dialog fragment object */
    alert.setArguments(b);

    /** Creating the dialog fragment object, which will in turn open the alert dialog window */

    alert.show(fm, "alert_dialog_post_delete");
}

public void onPostShare(final int position) {

    final Item item = itemsList.get(position);

    Api api = new Api(getActivity());
    api.postShare(item);
}

public void action(int position) {

    final Item item = itemsList.get(position);

    if (item.getFromUserId() == App.getInstance().getId()) {

        /** Getting the fragment manager */
        android.app.FragmentManager fm = getActivity().getFragmentManager();

        /** Instantiating the DialogFragment class */
        MyPostActionDialog alert = new MyPostActionDialog();

        /** Creating a bundle object to store the selected item's index */
        Bundle b  = new Bundle();

        /** Storing the selected item's index in the bundle object */
        b.putInt("position", position);

        /** Setting the bundle object to the dialog fragment object */
        alert.setArguments(b);

        /** Creating the dialog fragment object, which will in turn open the alert dialog window */

        alert.show(fm, "alert_my_post_action");

    } else {

        /** Getting the fragment manager */
        android.app.FragmentManager fm = getActivity().getFragmentManager();

        /** Instantiating the DialogFragment class */
        PostActionDialog alert = new PostActionDialog();

        /** Creating a bundle object to store the selected item's index */
        Bundle b  = new Bundle();

        /** Storing the selected item's index in the bundle object */
        b.putInt("position", position);

        /** Setting the bundle object to the dialog fragment object */
        alert.setArguments(b);

        /** Creating the dialog fragment object, which will in turn open the alert dialog window */

        alert.show(fm, "alert_post_action");
    }
}

public void showMessage(String message) {

    mMessage.setText(message);
    mMessage.setVisibility(View.VISIBLE);

    mSplash.setVisibility(View.VISIBLE);
}

public void hideMessage() {

    mMessage.setVisibility(View.GONE);

    mSplash.setVisibility(View.GONE);
}

public void onPostCreateChat(int position) {

    final Item item = itemsList.get(position);

    createChat(item.getFromUserId());
}

public void onPostFollow(int position) {

    final Item item = itemsList.get(position);

    Api api = new Api(getActivity());

    api.profileFollow(item.getFromUserId());
}

public void createChat(final long profileId) {

    if (App.getInstance().isConnected() && App.getInstance().getId() != 0) {

        CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_CHAT_NEW, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            if (!response.getBoolean("error")) {

                                Intent intent = new Intent(getActivity(), ChatActivity.class);
                                intent.putExtra("position", 0);
                                intent.putExtra("chatId", response.getInt("id"));
                                intent.putExtra("profileId", response.getLong("withUserId"));
                                intent.putExtra("chatTitle", response.getString("title"));

                                intent.putExtra("fromUserId", response.getLong("fromUserId"));
                                intent.putExtra("toUserId", response.getLong("toUserId"));

                                startActivityForResult(intent, 1);

                            } else {

                                Toast.makeText(getActivity(), getString(R.string.msg_chat_create_error), Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {

                            e.printStackTrace();

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getActivity(), getString(R.string.error_data_loading), Toast.LENGTH_SHORT).show();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("accountId", Long.toString(App.getInstance().getId()));
                params.put("accessToken", App.getInstance().getAccessToken());

                params.put("profileId", Long.toString(profileId));

                return params;
            }
        };

        int socketTimeout = 0;//0 seconds - change to what you want
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

        jsonReq.setRetryPolicy(policy);

        App.getInstance().addToRequestQueue(jsonReq);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}
  }

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

活动

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="image">
  </div>
  <div class="slider">
    <div class="title">Title</div>
    <div class="text">Text</div>
  </div>
</div>

BaseFragment 应该扩展Fragment,并且有一个名为 updateList()的方法。

BaseFragment visibleFragment = getViewPager().getItem(getPageAdapter.getCurrentItem());

BaseFragment 中:

visibleFragment.updateList();

// visibleFragment is the fragment visible to the user