使用BaseCardView和它的子类显示与媒体项相关的数据。使用ImageCardView显示显示图片和标题。
创建一个Card Presenter
Presenter根据需求生成视图并将数据对象与之绑定。
如下:
@Override
public void onLoadFinished(Loader<HashMap<String, List<Movie>>> arg0,
HashMap<String, List<Movie>> data) {
mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
CardPresenter cardPresenter = new CardPresenter();
int i = 0;
for (Map.Entry<String, List<Movie>> entry : data.entrySet()) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter);
List<Movie> list = entry.getValue();
for (int j = 0; j < list.size(); j++) {
listRowAdapter.add(list.get(j));
}
HeaderItem header = new HeaderItem(i, entry.getKey(), null);
i++;
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
HeaderItem gridHeader = new HeaderItem(i, getString(R.string.more_samples),null);
GridItemPresenter gridPresenter = new GridItemPresenter();
ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(gridPresenter);
gridRowAdapter.add(getString(R.string.grid_view));
gridRowAdapter.add(getString(R.string.error_fragment));
gridRowAdapter.add(getString(R.string.personal_settings));
mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter));
setAdapter(mRowsAdapter);
updateRecommendations();
}
注:每一个presenter只能创建一种视图类型,如果有多种不同视图类型就需要创建多种presenter。
创建Presenter需要实现onCreatViewHolder()方法:
@Override
public class CardPresenter extends Presenter {
private Context mContext;
private static int CARD_WIDTH = 313;
private static int CARD_HEIGHT = 176;
private Drawable mDefaultCardImage;
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent) {
mContext = parent.getContext();
mDefaultCardImage = mContext.getResources().getDrawable(R.drawable.movie);
...
如果卡片选中,你可以做各种操作,默认放大:
...
ImageCardView cardView = new ImageCardView(mContext) {
@Override
public void setSelected(boolean selected) {
int selected_background = mContext.getResources().getColor(R.color.detail_background);
int default_background = mContext.getResources().getColor(R.color.default_background);
int color = selected ? selected_background : default_background;
findViewById(R.id.info_field).setBackgroundColor(color);
super.setSelected(selected);
}
};
...
为了实现遥控操作需要设置 setFocusable(true),setFocusableInTouchMode(true):
...
cardView.setFocusable(true);
cardView.setFocusableInTouchMode(true);
return new ViewHolder(cardView);