android:将数据从适配器类发送到Activity

时间:2017-01-11 20:40:58

标签: java android

嘿,我想在用户点按图片时将照片添加到喜爱的活动中。到目前为止,我能够获取数据,但不知道如何将其传递给我最喜欢的活动。我应该如何处理这个问题,也许是使用意图和广播?任何帮助,将不胜感激。感谢

这是我的MyRecyclerAdapter类

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyViewHolder>{

    Context c;
    ArrayList<Album> albums;

    public MyRecyclerAdapter(Context c, ArrayList<Album> albums){
        this.c=c;
        this.albums=albums;
    }
    // Initialize holder
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

       View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
        MyViewHolder holder = new MyViewHolder(v);
       return holder;
    }

    //Bind data to views
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

      holder.nameTxt.setText(albums.get(position).getName());
      holder.img.setImageResource(albums.get(position).getImage());

     //listener
        holder.setItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(View v, int pos) {
                Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();


             //  albums.get(pos).getName();

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

这是我的MyViewHolder类

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

    ImageView img;
    TextView nameTxt;
    ItemClickListener itemClickListener;

    public MyViewHolder(View itemView) {

        super(itemView);

        nameTxt=(TextView) itemView.findViewById(R.id.nameTxt);
        img = (ImageView) itemView.findViewById(R.id.movieImage);

        itemView.setOnClickListener(this);



    }

    public void setItemClickListener(ItemClickListener ic)
    {
        this.itemClickListener=ic;

    }


    @Override
    public void onClick(View v) {

        this.itemClickListener.onItemClick(v,getLayoutPosition());


    }
}

1 个答案:

答案 0 :(得分:0)

假设您的图片位于可绘制文件夹中,可以通过以下行获取:albums.get(position).getImage()

然后只需将int值传递给您的FavoritesActivity:

Intent intent = new Intent(c, FavoritesActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, albums.get(pos).getImage());
c.startActivity(intent); // put context infront

请注意albums.get(pos).getImage()应该返回和int值。 然后在您的FavoritesActivity中通过调用以下内容进行检索:

myImageView = (ImageView) findViewById(R.id.my_image_view);

Intent intent = getIntent();
if (intent.hasExtra(Intent.EXTRA_TEXT)){
    int image = intent.getIntExtra(Intent.EXTRA_TEXT);
    myImageView.setImageResource(image);
}