如何在RecyclerView中创建不同的CardView布局

时间:2016-06-10 13:28:14

标签: android android-recyclerview

我已经阅读了一系列关于如何在recyclerview布局中放置不同宽度和高度的卡片布局的帖子。不幸的是,到目前为止没有人帮助过我。

我已经创建了GridLayout,如下所示,但我想创建一个显示在主卡布局顶部的单独卡片。在这种情况下,“紧急警报卡”。

以下是我想要实现的目标。

Grid Recycler View layout with heterogenous cardviews

我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity {
 private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a GridLayout manager
        mLayoutManager = new GridLayoutManager(this, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter
        List<ItemObject> rowListItem = getAllItemList();
        mAdapter = new CardViewDataAdapter(MainActivity.this, rowListItem);
        mRecyclerView.setAdapter(mAdapter);
}


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_help) {
            Intent intent = new Intent(this, help_activity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_about) {
            Intent intent = new Intent(this, about_activity.class);
            startActivity(intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //Handles the references to items displayed on each cards
    private List<ItemObject> getAllItemList() {

        List<ItemObject> allItems = new ArrayList<ItemObject>();
        allItems.add(new ItemObject("Fire", R.drawable.fire));
        allItems.add(new ItemObject("Ambulance", R.drawable.ambulance));
        allItems.add(new ItemObject("Police", R.drawable.police));
        allItems.add(new ItemObject("ERT", R.drawable.ert));
        allItems.add(new ItemObject("Safety Tips", R.drawable.safetytips));
        allItems.add(new ItemObject("First Aid", R.drawable.firstaid));
        return allItems;
    }

    private ArrayList<Object> getSampleArrayList() {
        ArrayList<Object> items = new ArrayList<>();
        items.add(new ItemObject("Dany Targaryen", R.drawable.click));

        return items;
    }

CardViewDataAdapter.java

public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {

    private List<ItemObject> itemList;
    private static final int TYPE_IMAGE = 1;
    private static final int TYPE_GROUP = 2;

    public CardViewDataAdapter(Context context, List<ItemObject> itemList) {
        this.itemList = itemList;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                             int viewType) {
        // create a new view
        View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.cardview_row, null);

        //Todo: set the view's size, margins, paddings and layout parameters
        // create ViewHolder
        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;

    }

    public class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView mImage;
        public ImageViewHolder(View itemView) {
            super (itemView);
            // init views...
        }
    }

    @Override
    public int getItemViewType(int position) {
        // here your custom logic to choose the view type
        return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
    }


    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {

        // - get data from your itemsData at this position
        // - replace the contents of the view with that itemsData
        viewHolder.image_view.setImageResource(itemList.get(position).getPhoto());
        viewHolder.image_name.setText(itemList.get(position).getName());


    }


    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return this.itemList.size();
    }

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    // inner class to hold a reference to each item of RecyclerView
    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        // each data item is a string and an image in this case
        public ImageView image_view;
        public TextView image_name;
        public Context context;


        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);
            this.image_view = (ImageView) itemLayoutView.findViewById(R.id.image_view);
            this.image_name = (TextView) itemLayoutView.findViewById(R.id.image_name);

            itemLayoutView.setOnClickListener(this);
            itemLayoutView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Toast.makeText(v.getContext(), "OnLongClick Coming soon! :" + getAdapterPosition(),
                            Toast.LENGTH_SHORT).show();
                    return true;
                }
            });

        }

1 个答案:

答案 0 :(得分:1)

一种解决方案是使用StaggeredGridLayoutManager作为回收站视图的布局管理器。然后,您可以将视图持有者配置为跨越视图的整个宽度。

将布局管理器更改为StaggeredGridLayoutManager

mRecyclerView.setLayoutManager(
    new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

然后在onBind中,检查您的第一个项目(紧急卡),并更改其布局参数以启用完整范围:

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

    // - get data from your itemsData at this position
    // - replace the contents of the view with that itemsData
    viewHolder.image_view.setImageResource(itemList.get(position).getPhoto());
    viewHolder.image_name.setText(itemList.get(position).getName());

    if(position == 0) {
        StaggeredGridLayoutManager.LayoutParams params = 
            (StaggeredGridLayoutManager.LayoutParams) viewHolder.getLayoutParams();
        params.setFullSpan(true);

        viewHolder.itemView.setLayoutParams(params);
    }
}