0

我有 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()));
}

这是我的专辑适配器:

公共类 AlbumsAdapter 扩展 RecyclerView.Adapter { Context mContext; 列出专辑列表;

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 中的每个封面添加 SetOnClickListener。怎么做?请帮帮我

4

2 回答 2

1

由于您使用的是 RecyclerView.. 请按照此方法将点击事件实现到 RecyclerView 元素..

1、创建监听接口类。

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

2.在adapter类中声明item click listener

ItemClickListener clickListener;

3、在ViewHolder的构造函数中添加onClick监听,在Viewholder类里面定义函数。不要忘记实现 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.在适配器内部定义click函数

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

5.在MainActivity上实现ItemClickListener

public class MainActivity extends Activity implements ItemClickListener

6.在MainActivity中定义onClick()函数

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.调用adapter.Onclick

myAdapter.setClickListener(this);
于 2016-08-30T04:37:37.197 回答
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));

        }
    });
}
于 2016-08-30T04:07:02.723 回答