簡體   English   中英

將RecyclerView CardView單擊項目數據傳遞給活動

[英]Passing RecyclerView CardView Clicked Item Data To Activity

我有一個關於將點擊的cardview數據傳遞給活動的問題,這里有完整的故事:

  1. 我有一個名為“詳細信息”的活動,其中包含2個TextViews的布局,標題和描述。

  2. 我已經設置了一個片段(tab_1),其中包含recyclerview代碼和items數據,每個項目包含:標題和描述。

我想要的是 :

當用戶單擊該項目時,它將打開詳細信息活動,並更改詳細信息布局標題,單擊項目標題,以及相同的描述。

我已經創建了另一個活動作為一個例子,並且意圖啟動它,再加上“addOnTouchlistener”,感謝Stackoverflow,我找到了實現它的方法。

那么,如何使這個活着? 我已經在Stackoverflow上嘗試了許多可用答案的方法,但所有這些方法都不起作用,或者與我的請求無關。

這是我的文件:

itemsdata.java:

public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;

tab_1.java(片段)

public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {

private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.tab_1, container, false);
    mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
    mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
            (getContext(), new RecyclerItemClickListener.OnItemClickListener() {

                @Override
                public void onItemClick(View view, int position) {
                    Intent i = new Intent(view.getContext(), DetailsActivity.class);
                    view.getContext().startActivity(i);
                }
            }));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    adapter = new RecyclingViewAdapter(getActivity(),Listed());
    mRecyclerView.setAdapter(adapter);
    return layout;

}


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.main, menu);

    final MenuItem item = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
    searchView.setOnQueryTextListener(this);
}

@Override
public boolean onQueryTextChange(String query) {
    final List<itemsdata> filteredModelList = filter(Listed(), query);
    adapter.animateTo(filteredModelList);
    mRecyclerView.scrollToPosition(0);
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    return true;
}

private List<itemsdata> filter(List<itemsdata> models, String query) {
    query = query.toLowerCase();

    final List<itemsdata> filteredModelList = new ArrayList<>();
    for (itemsdata model : models) {
        final String text = model.title.toLowerCase();
        if (text.contains(query)) {
            filteredModelList.add(model);
        }
    }
    return filteredModelList;
}

public List<itemsdata> Listed()
{
    //Titles Strings
    String sys_title1 = getString(R.string.system_item_title_1);
    String sys_title2 = getString(R.string.system_item_title_2);
    String sys_title3 = getString(R.string.system_item_title_3);

    //Description Strings
    String sys_descr1 = getString(R.string.system_item_desc_1);
    String sys_descr2 = getString(R.string.system_item_desc_2);
    String sys_descr3 = getString(R.string.system_item_desc_3);

    //Adding New Cards
    List<itemsdata> data = new ArrayList<>();

    //Categories Icons New Items ** Make It The Same
    int[] icons = {
            R.drawable.facebook_icon ,
            R.drawable.twitter_icon ,
            R.drawable.twitter_icon
    };

    //Expand Button New Items
    int[] expandbutton = {
            R.drawable.expanded ,
            R.drawable.expanded ,
            R.drawable.expanded
    };

    //UnExpand Button New Items
    int[] unexpandbutton = {
            R.drawable.ca_expand ,
            R.drawable.ca_expand ,
            R.drawable.ca_expand
    };

    //Titles New Items
    String[] titles = {
            sys_title1 ,
            sys_title2 ,
            sys_title3
    };

    //Description New Items
    String[] Description = {
            sys_descr1 ,
            sys_descr2 ,
            sys_descr3
    };


    for(int i = 0;i<titles.length && i < icons.length  && i < Description.length && i < unexpandbutton.length && i < expandbutton.length  ; i++)
    {
        itemsdata current = new itemsdata();
        current.CatPic = icons[i];
        current.title = titles[i];
        current.Descr = Description[i];
        current.expand_no = unexpandbutton[i];
        current.Exapnd = expandbutton[i];
        data.add(current);
    }
    return data;
}

}

詳情活動:

public class DetailsActivity extends AppCompatActivity{

TextView title;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.details);
    title = (TextView)findViewById(R.id.details_title);
}

編輯:我已經做到了,我已經添加了一個打開片段的按鈕,並在適配器中傳遞數據,但我希望它通過tab_1.java,而不是適配器,我的意思是我想點擊項目到打開片段,而不是按鈕,這里是我的適配器代碼的快照(我已經在OnBindViewHolder中添加了它)

我已經設置了OnClick並實現了Vew.setOnClick ..etc,但是當我點擊該項目時,沒有任何反應。

 @Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(v.getContext(),DetailsActivity.class);
            v.getContext().startActivity(i);
        }
    });

    //Referencing Data
    final itemsdata currentobject = mdata.get(position);
    //Referencing Items
    holder.ProbTitle.setText(currentobject.title);
    holder.ProbDescr.setText(currentobject.Descr);
    holder.CategoryPic.setImageResource(currentobject.CatPic);
    holder.ExpandButton.setImageResource(currentobject.Exapnd);
    holder.ExpandNoButton.setImageResource(currentobject.expand_no);
        //What Happen When You Click Expand Button .
    holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(v.getContext(), DetailsActivity.class);
            i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
            v.getContext().startActivity(i);
            }
        }
    );

public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{



    SwipeLayout swipeLayout;
    //Defining Items .
    TextView ProbTitle;
    ImageButton ExpandButton;
    TextView ProbDescr;
    ImageButton ExpandNoButton;
    ImageView CategoryPic;
    /*
    TextView Card_Star;
    TextView Card_UnStar;
    */
    TextView Card_Share;

    //Referencing Resources
    public MyRecycleViewHolder(final View itemView) {
        super(itemView);
        ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
        CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
        ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
        ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
        ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
        /*
        Card_Star = (TextView) itemView.findViewById(R.id.card_star);
        Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
        */
        Card_Share = (TextView) itemView.findViewById(R.id.card_share);
        swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);

    }

在包含methods的適配器中創建一個Interface 在實現適配器時,這些方法將在您的活動中實現,您可以執行您想要的任何操作。

    public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {

    public interface Callbacks {
        public void onButtonClicked(String titleKey);
    }

    private Callbacks mCallbacks;

    public Adapter() {

    }

    @Override
    public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
        return new MyRecycleViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {

        holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCallbacks != null) {
                    mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
                }
            }
        });

    }


    @Override
    public int getItemCount() {
        return;
    }

    public void setCallbacks(Callbacks callbacks) {
        this.mCallbacks = callbacks;
    }
}   

您可以嘗試在onItemClick()上執行此操作

Intent i = new Intent(view.getContext(), DetailsActivity.class); i.putExtra("title", yourTitle); i.putExtra("description", yourDescription); view.getContext().startActivity(i);

當您在DetailActivity中創建oncreate時,請執行此操作

String title = getIntent().getStringExtra("title"); String description = getIntent().getStringExtra("description");

所以你可以將標題和描述傳遞給DetailActivity

首先使你的“itemsdata”對象實現Parcelable。 你可以在這里查看 在onItemClick方法中,使用intent.putExtra(“key”,listOfDataItems.get(position))將對象傳遞給Details活動。 在您的DetailsActivity中,您可以使用getParcelable(“key”)獲取自定義對象

所有上述方法都有效,但有點長,所以這個方法對我有用:

Cardview cardview;
            cardView = (CardView)itemView.findViewById(R.id.cv);

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent (view.getContext(), DetailsActivity.class);
                i.putExtra("TitleKey",ProbTitle.getText().toString());
                i.putExtra("DescrKey",ProbDescr.getText().toString());
                view.getContext().startActivity(i);
            }
        });

在Details.java中:

    TextView title;
TextView Descr;
        title = (TextView)findViewById(R.id.details_title);
    Descr = (TextView)findViewById(R.id.details_descr);

    String titleresult = result.getExtras().getString("TitleKey");
    String Descrresult = result.getExtras().getString("DescrKey");

    title.setText(titleresult);
    Descr.setText(Descrresult);

IMO,您在RecyclerView Adapter中實現了setOnClickListener 您可以參考我的以下示例代碼,然后將其邏輯應用於您的代碼。 希望能幫助到你!

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

    Context mContext;
    List<String> mStringList;

    public MyRVAdapter(Context mContext, List<String> mStringList) {
        this.mContext = mContext;
        this.mStringList = mStringList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView textView1 = (TextView) v.findViewById(R.id.textView1);
                TextView textView2 = (TextView) v.findViewById(R.id.textView2);
                Bundle bundle = new Bundle();
                bundle.putString("key1", textView1.getText().toString());
                bundle.putString("key2", textView2.getText().toString());

                passToAnotherActivity(bundle);
            }
        });
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // do something...
    }

    @Override
    public int getItemCount() {
        if (mStringList != null) {
            return mStringList.size();
        }
        return 0;
    }

    private void passToAnotherActivity(Bundle bundle) {
        if (mContext == null)
            return;
        if (mContext instanceof MainActivity) {
            MainActivity activity = (MainActivity) mContext;
            activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public ViewHolder(View itemView) {
            super(itemView);
            // do something...
        }

        @Override
        public void onClick(View v) {
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM