在TabFragment中的RecyclerView中加载了错误的项目

时间:2016-11-28 15:08:35

标签: android android-recyclerview android-adapter android-tablayout

我有一个非常奇怪的问题。我的MainActivity TabFragment包含4个标签。其中3个选项卡具有相同的样式和线程列表。这三个标签是ActiveWatchingI'm On。我遇到的问题是,当我点击Watching中的某个项目时,它会从Active中的相同位置加载该主题。我已经在我的适配器中实现了onClick,因为它只是我想要点击的RecyclerView的某个部分才能通向此页面而另一部分则打开上下文菜单。

我不知道如何解决这个问题,我甚至不确定标题是否与帖子匹配,因为我不知道我实际上想要搜索什么。

这是我在三个片段中的任何一个中设置适配器的代码

mAdapter = new WatchedThreadAdapter(getContext(), mData);
mRecyclerView.setAdapter(mAdapter);

这里是适配器内的onClick

mContext.startActivity(ActivePostPagerActivity.createIntent(mContext, position));

我的WatchingFragment看起来像这样:

    public class WatchingFragment extends Fragment {

    private View mRootView;
    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private ThreadResponse mData;
    private WatchedThreadsRequestData mRequestData;
    private RecyclerView.Adapter mAdapter;
    private TextView mNoThreadTextView;
    private int mDataSize;

    private MyReceiver r;


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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_watching, container, false);

        if (savedInstanceState == null) {
            initUI();
        }

        return mRootView;
    }

    private void initUI() {
        mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.watchedThreadRecyclerView);
        mNoThreadTextView = (TextView) mRootView.findViewById(R.id.noWatchedThreads);
        mLayoutManager = new GridLayoutManager(getActivity(), 1);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRequestData = new WatchedThreadsRequestData(getActivity());
        registerForContextMenu(mRecyclerView);

/*        mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
                (getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        showItemSelectedAtPosition(position);

                    }
                }));*/

        loadData();

    }

    private void loadData() {
        mRequestData.getWatchedData(new WatchedThreadsRequestData.WatchedThreadsFeedback() {
            @Override
            public void onWatchedRequestReceived(ThreadResponse response) {
                mData = response;
                populateUIWithData();
                mDataSize = mData.getItems().size();
            }

            @Override
            public void onWatchedRequestFailed(Exception exception) {

            }
        });
    }

    private void populateUIWithData() {

        if (mData.getItems().size() == 0) {
            mNoThreadTextView.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            mAdapter = new WatchedThreadAdapter(getContext(), mData);
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
            mRecyclerView.setVisibility(View.VISIBLE);
            mNoThreadTextView.setVisibility(View.GONE);
        }

        if (mData.getItems() != null && mData.getItems().size() > mDataSize) {
            mAdapter.notifyDataSetChanged();
            mDataSize = mData.getItems().size();
        }

    }

/*    private void showItemSelectedAtPosition(int position) {
        Threads selectedThread = mData.getItem(position);

        Intent intent = new Intent(getActivity(), ActivePostPagerActivity.class);
        intent.putExtra("Threads", Parcels.wrap(selectedThread.getThreadItem()));
        intent.putExtra("ActiveTitle", "Watching");

        startActivity(intent);

    }*/

    public void refresh() {

        Log.i("Refresh", "YES");

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.detach(this).attach(this).commit();

    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(r);
    }

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

        r = new MyReceiver();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(r,
                new IntentFilter("TAG_REFRESH"));

    }



    public class MyReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            WatchingFragment.this.refresh();
        }
    }

}

并且WatchingAdapter看起来像这样

    public class WatchedThreadAdapter extends RecyclerView.Adapter<WatchedThreadAdapter.ViewHolder> {

    private Context mContext;
    private ThreadResponse mThread;
    private String mShareURL, mThreadID;
    private WatchedThreadsRequestData watchedThreadsRequestData;
    private HiddenThreadsRequest hiddenThreadsRequest;
    public static final int GALLERY_VIEW = 800;
    private boolean isWatched = false;
    private PopupMenu popupMenu;
    private MenuItem watchedMenuItem;

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener, PopupMenu.OnMenuItemClickListener {

        private TextView mThreadText, mTopicText, mNumPosts;
        private View mStickyView;
        private ImageButton mMoreOptionsButton;
        private LinearLayout mThreadTitleContainer;

        public ViewHolder(View v) {
            super(v);
            mThreadText = (TextView) v.findViewById(R.id.threadText);
            mTopicText = (TextView) v.findViewById(R.id.topicText);
            mNumPosts = (TextView) v.findViewById(R.id.numPosts);
            mStickyView = v.findViewById(R.id.sticky);
            mMoreOptionsButton = (ImageButton) v.findViewById(R.id.moreOptions);
            mThreadTitleContainer = (LinearLayout) v.findViewById(R.id.threadTitleContainer);
            mMoreOptionsButton.setOnClickListener(this);

            final View optionsButtonParent = (View) mMoreOptionsButton.getParent();
            optionsButtonParent.post(new Runnable() {
                @Override
                public void run() {
                    Rect rect = new Rect();
                    mMoreOptionsButton.getHitRect(rect);
                    rect.top -= 10;    // increase top hit area
                    rect.left -= 10;   // increase left hit area
                    rect.bottom += 10; // increase bottom hit area
                    rect.right += 10;  // increase right hit area
                    optionsButtonParent.setTouchDelegate(new TouchDelegate(rect, mMoreOptionsButton));
                }
            });

            final View numPostsParent = (View) mNumPosts.getParent();
            optionsButtonParent.post(new Runnable() {
                @Override
                public void run() {
                    Rect rect = new Rect();
                    mNumPosts.getHitRect(rect);
                    rect.top -= 20;    // increase top hit area
                    rect.left -= 20;   // increase left hit area
                    rect.bottom += 20; // increase bottom hit area
                    rect.right += 20;  // increase right hit area
                    numPostsParent.setTouchDelegate(new TouchDelegate(rect, mNumPosts));
                }
            });

        }


        @Override
        public void onClick(View v) {
            if (v == mMoreOptionsButton) {
                popupMenu = new PopupMenu(v.getContext(), v);
                popupMenu.inflate(R.menu.thread_options);
                popupMenu.getMenu();
                popupMenu.setOnMenuItemClickListener(this);
                setForceShowIcon(popupMenu);
                popupMenu.show();

                if (PreferenceConnector.readString(mContext, "share") != null) {
                    mShareURL = PreferenceConnector.readString(mContext, "share");
                }

                if (PreferenceConnector.readString(mContext, "threadID") != null) {
                    mThreadID = PreferenceConnector.readString(mContext, "threadID");
                }

                watchedMenuItem = popupMenu.getMenu().findItem(R.id.watch);

                if (mThread.getItem(getPosition()) != null && mThread.getItem(getPosition()).getThreadItem() != null) {
                    if (mThread.getItem(getAdapterPosition()).getThreadItem().getWatched() == 1) {
                        watchedMenuItem.setTitle("Unwatch");
                    } else {
                        watchedMenuItem.setTitle("Watch");
                    }
                }

            }

        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {

            switch (item.getItemId()) {

                case R.id.watch:
                    if (PreferenceConnector.readString(mContext, "authToken") == null) {
                        final AlertDialog.Builder loginDialog = new AlertDialog.Builder(mContext);
                        loginDialog.setTitle("You're not logged in")
                                .setMessage("You need to be logged in to be able to watch a thread")
                                .setPositiveButton("Login", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent loginIntent = new Intent(mContext, LoginActivity.class);
                                        mContext.startActivity(loginIntent);
                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        AlertDialog dialog = loginDialog.create();

                        dialog.show();
                    } else if (mThread.getItem(getAdapterPosition()) != null && mThread.getItem(getAdapterPosition()).getThreadItem() != null
                            && mThread.getItem(getAdapterPosition()).getThreadItem().getWatched() == 0) {
                        watchedThreadsRequestData = new WatchedThreadsRequestData(mContext);
                        watchedThreadsRequestData.setWatchedThread(mThreadID, new WatchedThreadsRequestData.WatchedThreadsFeedback() {
                            @Override
                            public void onWatchedRequestReceived(ThreadResponse response) {
                                mThread = response;
                                Toast.makeText(mContext, "Thread watched",
                                        Toast.LENGTH_SHORT).show();

                                watchedMenuItem.setTitle("Unwatch");
                            }

                            @Override
                            public void onWatchedRequestFailed(Exception exception) {
                                Toast.makeText(mContext, "Thread wasn't watched: " + exception.toString(), Toast.LENGTH_LONG).show();

                            }
                        });

                        isWatched = true;

                    } else {
                        watchedThreadsRequestData = new WatchedThreadsRequestData(mContext);
                        watchedThreadsRequestData.removeWatchedThread(mThreadID, new WatchedThreadsRequestData.WatchedThreadsFeedback() {
                            @Override
                            public void onWatchedRequestReceived(ThreadResponse response) {
                                mThread = response;
                                Toast.makeText(mContext, "Thread unwatched", Toast.LENGTH_SHORT).show();

                                watchedMenuItem.setTitle("Watch");

                            }

                            @Override
                            public void onWatchedRequestFailed(Exception exception) {

                            }
                        });

                        isWatched = false;


                    }
                    return true;
                case R.id.shareThread:
                    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                    sharingIntent.putExtra(Intent.EXTRA_TEXT, mShareURL);
                    sharingIntent.setType("text/plain");
                    mContext.startActivity(Intent.createChooser(sharingIntent, "Share via"));
                    return true;
                case R.id.hideThread:
                    if (PreferenceConnector.readString(mContext, "authToken") == null) {
                        final AlertDialog.Builder loginDialog = new AlertDialog.Builder(mContext);
                        loginDialog.setTitle("You're not logged in")
                                .setMessage("You need to be logged in to be able to hide a thread")
                                .setPositiveButton("Login", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent loginIntent = new Intent(mContext, LoginActivity.class);
                                        mContext.startActivity(loginIntent);
                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        AlertDialog dialog = loginDialog.create();

                        dialog.show();
                    } else {

                        if (mThread.getItem(getAdapterPosition()).getThreadItem().isSticky()) {

                            Toast.makeText(mContext, "You can't hide a this thread.",
                                    Toast.LENGTH_SHORT).show();


                        } else {

                            hiddenThreadsRequest = new HiddenThreadsRequest(mContext);
                            hiddenThreadsRequest.setHiddenThread(mThreadID, new HiddenThreadsRequest.HiddenThreadsFeedback() {
                                @Override
                                public void onHiddenRequestReceived(ThreadResponse response) {

                                    Toast.makeText(mContext, "Thread hidden",
                                            Toast.LENGTH_SHORT).show();

                                    removeAt(getPosition());

                                }

                                @Override
                                public void onHiddenRequestFailed(Exception exception) {

                                    Toast.makeText(mContext,
                                            "Oops! Something went wrong there, please try again",
                                            Toast.LENGTH_SHORT).show();

                                }
                            });
                        }
                    }
                    return true;
                default:
                    Toast.makeText(mContext, "Somethings Wrong",
                            Toast.LENGTH_SHORT).show();
                    return true;
            }
        }

    }

    public WatchedThreadAdapter(Context context, ThreadResponse response) {
        mContext = context;
        mThread = response;

        if (mThread == null) {
            mThread = new ThreadResponse();
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;

        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_thread, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final Threads threadItem = mThread.getItem(position);

        if (threadItem.getThreadItem() != null) {

            if (threadItem.getThreadItem().getName() != null)
                holder.mThreadText.setText(threadItem.getThreadItem().getName());

            holder.mThreadTitleContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showItemSelectedAtPosition(holder.getAdapterPosition());
                }
            });

            holder.mThreadText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showItemSelectedAtPosition(holder.getAdapterPosition());
                }
            });

            holder.mNumPosts.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showItemSelectedAtPosition(holder.getAdapterPosition());
                }
            });

            if (threadItem.getThreadItem().getTopic_name() != null) {
                holder.mTopicText.setText(threadItem.getThreadItem().getTopic_name());
                holder.mTopicText.setAlpha(0.7f);
            }

            if (threadItem.getThreadItem().getNum_posts() != null) {
                int numPosts = Integer.parseInt(threadItem.getThreadItem().getNum_posts());
                if (numPosts > 1000) {
                    holder.mNumPosts.setText("1K");
                } else {
                    holder.mNumPosts.setText(threadItem.getThreadItem().getNum_posts());
                }

            }

            if (threadItem.getThreadItem().isSticky()) {
                holder.mStickyView.setVisibility(View.VISIBLE);
            } else {
                holder.mStickyView.setVisibility(View.GONE);
            }

            if (threadItem.getThreadItem().getThread_url() != null) {
                PreferenceConnector.writeString(mContext, "share", threadItem.getThreadItem().getName()
                        + " - " + Constants.DEV_URL + "talk/" +
                        threadItem.getThreadItem().getTopic_url() + '/' +
                        threadItem.getThreadItem().getThread_url());
            }

            if (threadItem.getThreadItem().getId() != null) {
                PreferenceConnector.writeString(mContext, "threadID", threadItem.getThreadItem().getId());
            }

        }

    }

    @Override
    public int getItemCount() {
        return mThread.getItems().size();
    }

    public static void setForceShowIcon(PopupMenu popupMenu) {
        try {
            Field[] fields = popupMenu.getClass().getDeclaredFields();
            for (Field field : fields) {
                if ("mPopup".equals(field.getName())) {
                    field.setAccessible(true);
                    Object menuPopupHelper = field.get(popupMenu);
                    Class<?> classPopupHelper = Class.forName(menuPopupHelper
                            .getClass().getName());
                    Method setForceIcons = classPopupHelper.getMethod(
                            "setForceShowIcon", boolean.class);
                    setForceIcons.invoke(menuPopupHelper, true);
                    break;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private void showItemSelectedAtPosition(int position) {

        PreferenceConnector.writeBoolean(mContext, "fromNewThread", false);

        mContext.startActivity(ActivePostPagerActivity.createIntent(mContext, position));

//        mContext.startActivityForResult(ActivePostPagerActivity.createIntent(mContext, position), GALLERY_VIEW);


    }

    public void removeAt(int position) {

        mThread.getItems().remove(position);
        notifyItemRemoved(position);
        notifyItemChanged(position, mThread.getItems().size());

    }


}

如果您需要任何其他信息,请不要犹豫。非常感谢你的时间和耐心。

1 个答案:

答案 0 :(得分:0)

我想通了,在我的ActivePostPager.createInstance()方法中,我硬编码检查以查看页面的位置。它现在已经解决了!!