搜尋此網誌

2015年9月19日 星期六

【Android】how to open a different fragment on recyclerview OnClick

ref:
http://stackoverflow.com/a/30434250

So simplified version, here's my onbindVH:
 @Override
    public void onBindViewHolder(FeedsViewHolder holder, int position) {
        final Feed item = mFeeds.get(position);

        holder.textView1.setText(item.getText());
        holder.imageView.setImageDrawable(mContext.getResources().getDrawable(item.getImage));
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentJump(item);
            }
        });
    }
here's fragmentJump:
private void fragmentJump(Feed mItemSelected) {
    mFragment = new Fragment2();
    mBundle = new Bundle();
    mBundle.putParcelable("item_selected_key", mItemSelected);
    mFragment.setArguments(mBundle);
    switchContent(R.id.frag1, mFragment);
}
here's switchContent on the adapter:
public void switchContent(int id, Fragment fragment) {
    if (mContext == null)
        return;
    if (mContext instanceof MainActivity) {
        MainActivity mainActivity = (MainActivity) mContext;
        Fragment frag = fragment;
        mainActivity.switchContent(id, frag);
    }

}
and lastly, here's the switchContent on MainActivity:
public void switchContent(int id, Fragment fragment) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(id, fragment, fragment.toString());
    ft.addToBackStack(null);
    ft.commit();
}
I know it can still be simplified, but it works as is. I hope it helps. :)

沒有留言: