【问题标题】:Intents inside a Recycler View?Recycler 视图中的意图?
【发布时间】:2015-01-02 17:10:52
【问题描述】:

谁能帮帮我!无法以正常的方式编写意图以在我的回收站视图中启动新活动来工作!有没有必须做的新方法?任何帮助将不胜感激!

这是我的视图持有者代码;

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView title;
    ImageView icon;

    public MyViewHolder(View itemView, TextView textView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.listText);
        icon = (ImageView) itemView.findViewById(R.id.listImage);
        itemView.setOnClickListener(this);
        title = textView;
    }

    @Override
    public void onClick(View v) {
        if (getPosition() == 0) {
            Toast.makeText(v.getContext(), "Actvity 1", Toast.LENGTH_SHORT).show();
        }
        if (getPosition() == 1) {
            Toast.makeText(v.getContext(), "Actvity 2", Toast.LENGTH_SHORT).show();
        }
    }
  }
}

【问题讨论】:

    标签: android android-intent onclick android-5.0-lollipop android-recyclerview


    【解决方案1】:

    viewHolder 中的初始点击监听器。

    /**
     * see {@link <a href="https://youtu.be/imsr8NrIAMs?t=2163">Official Video</a>}
     */
    public static class MyViewHolder extends RecyclerView.ViewHolder {
    
      public MyViewHolder(View itemView) {
        super(itemView);
        //TODO: findViewById or ButterKnife
        ....
        //set item view listener
        itemView.setOnClickListener(new View.OnClickListener() {
          @Override public void onClick(View itemView) {
            if (getAdapterPosition() != RecyclerView.NO_POSITION) {
              Context c = itemView.getContext();
              //TODO: startActivity
            }
          }
        });
        //TODO: set other child views' listener
        ....
      }
    }
    

    【讨论】:

      【解决方案2】:

      在您的自定义适配器中创建您自己的构造函数。 例如:

        private Context context;
          public MyRecyclerViewAdapter(Context context,ArrayList<String> yourList){
                  this.context=context;
                  // further code
          }
      

      在调用你的适配器时,只需传递你的上下文的引用,现在你就可以通过调用意图了

      context.startActivity() 和所有其他方法。

      【讨论】:

        【解决方案3】:

        ViewHolder 只是项目特定布局中内部View 对象的容器。它或您的实现的RecyclerView.Adapter 都不能直接访问发送Intent 所需的Context 对象。与其在此处设置OnClickListener,不如将​​其放在适配器的onBindViewHolder() 中。您的适配器可以在其拥有的RecyclerView 附加到它时收到通知,因此您可以在私有字段中保存对它的引用。从该视图中,您可以调用getContext(),然后您可以创建一个Intent 并通过通常的方式发送它。

        【讨论】:

        • ViewHolder 可以访问根视图,因此它也可以访问上下文
        • 啊,你说得对,我忘记了那个细节。我通常把它留给 Adapter 或拥有的 Fragment(使用接口)来处理点击/触摸交互,而不是把它放在这里。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多