如何为CardView中的每个项添加setOnClickListener

时间:2016-08-30 04:01:12

标签: android cardview

我有MainAcitivty.java

private AlbumsAdapter adapter;
private List<Album> albumList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    initCollapsingToolbar();

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    albumList = new ArrayList<>();
    adapter = new AlbumsAdapter(this, albumList);

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);


    prepareAlbums();

    try {
        Glide.with(this).load(R.drawable.cover).into((ImageView) findViewById(R.id.backdrop));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Initializing collapsing toolbar
 * Will show and hide the toolbar title on scroll
 */
private void initCollapsingToolbar() {
    final CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbar.setTitle(" ");
    AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
    appBarLayout.setExpanded(true);

    // hiding & showing the title when toolbar expanded & collapsed
    appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
        boolean isShow = false;
        int scrollRange = -1;

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (scrollRange == -1) {
                scrollRange = appBarLayout.getTotalScrollRange();
            }
            if (scrollRange + verticalOffset == 0) {
                collapsingToolbar.setTitle(getString(R.string.app_name));
                isShow = true;
            } else if (isShow) {
                collapsingToolbar.setTitle(" ");
                isShow = false;
            }
        }
    });
}

/**
 * Adding few albums for testing
 */
private void prepareAlbums() {
    int[] covers = new int[]{
            R.drawable.album1,
            R.drawable.album2,
            R.drawable.album3,
            R.drawable.album4,
            R.drawable.album5,
            R.drawable.album6,
            R.drawable.album7,
            R.drawable.album8,
            R.drawable.album9,
            R.drawable.album10,
            R.drawable.album11}
            ;

    Album a = new Album("True Romance", 13, covers[0] );

    albumList.add(a);


    a = new Album("Xscpae", 8, covers[1]);
    albumList.add(a);

    a = new Album("Maroon 5", 11, covers[2]);
    albumList.add(a);

    a = new Album("Born to Die", 12, covers[3]);
    albumList.add(a);

    a = new Album("Honeymoon", 14, covers[4]);
    albumList.add(a);

    a = new Album("I Need a Doctor", 1, covers[5]);
    albumList.add(a);

    a = new Album("Loud", 11, covers[6]);
    albumList.add(a);

    a = new Album("Legend", 14, covers[7]);
    albumList.add(a);

    a = new Album("Hello", 11, covers[8]);
    albumList.add(a);

    a = new Album("Greatest Hits", 17, covers[9]);
    albumList.add(a);

    adapter.notifyDataSetChanged();
}

/**
 * RecyclerView item decoration - give equal margin around grid item
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}

这是我的AlbumAdapter:

公共类AlbumsAdapter扩展了RecyclerView.Adapter {     上下文mContext;     列出albumList;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title, count;
    public ImageView thumbnail, overflow;

    public MyViewHolder(View view) {

        super(view);
        title = (TextView) view.findViewById(R.id.title);
        count = (TextView) view.findViewById(R.id.count);
        thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
        overflow = (ImageView) view.findViewById(R.id.overflow);

    }

}

public AlbumsAdapter(Context mContext, List<Album> albumList) {
    this.mContext = mContext;
    this.albumList = albumList;


}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.album_card, parent, false);

    return new MyViewHolder(itemView);
}

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

    Album album = albumList.get(position);
    holder.title.setText(album.getName());

    holder.count.setText(album.getNumOfSongs() + " songs");

    // loading album cover using Glide library
    Glide.with(mContext).load(album.getThumbnail()).into(holder.thumbnail);

    holder.overflow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showPopupMenu(holder.overflow);
        }
    });
}

private void showPopupMenu(View view) {
    PopupMenu popup = new PopupMenu(mContext, view);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.menu_album, popup.getMenu());
    popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
    popup.show();


}

class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {

    public MyMenuItemClickListener() {
    }

    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.action_add_favourite:
                Toast.makeText(mContext, "Add to favourite", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_play_next:
                Toast.makeText(mContext, "Play next", Toast.LENGTH_SHORT).show();
                return true;
            default:
        }
        return false;
    }
}

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

我想为Cardview中的每个Cover添加SetOnClickListener。怎么做?请帮帮我

2 个答案:

答案 0 :(得分:1)

Since you are using RecyclerView.. follow this method to implement click event to RecyclerView element..

1. Create a listener interface class.

public interface ItemClickListener {
    void onClick(View view, int position);
}

2. Declare item click listener in adapter class

ItemClickListener clickListener;

3. Add onClick listener to the constructor of ViewHolder and define the function inside the Viewholder class. Don't forget to implement View.OnClickListener

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

    TextView name,number;
    View circle;

    public MyViewHolder(View itemView) {
        super(itemView);

        name=(TextView)itemView.findViewById(R.id.txtName);
        number=(TextView) itemView.findViewById(R.id.txtNumber);
        circle = itemView.findViewById(R.id.circle);
        itemView.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
    }
}

4. Define click function inside the adapter

public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}

5. Implement ItemClickListener on MainActivity

public class MainActivity extends Activity implements ItemClickListener

6. Define onClick() function in MainActivity

public void onClick(View view, int position) {
    final Contact contact = contactList.get(position);
    Intent intent = new Intent(MainActivity.this, DetailedActivity.class);
    intent.putExtra("name",contact.getName());


}

7. Call adapter.Onclick

myAdapter.setClickListener(this);

答案 1 :(得分:0)

在onBindViewHolder中像这样调用你的onClickListener

@Override
public void onBindViewHolder(final FeedViewHolder holder, final int position) {
    holder.carName.setText(mCarNames[position]);
    holder.carLogo.setImageResource(mCarLogos[position]);

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mContext.startActivity(new Intent(mContext, AvailibilityActivity.class));

        }
    });
}