Search code examples
androidandroid-recyclerviewandroid-cardviewdashboard

RecyclerView with CardView as Dashboard or like a Windows Tiles


I spent many time looking for the solution How to do the Windows tiles liked interface, also knowing as Dashboard. I want use for it RecyclerView with CardView. I found old solution but there used LinearLayout with Buttons: How to create layout with 6 buttons like windows tiles

What I have at this moment: enter image description here

What I want: enter image description here

I have six CardViews, they should occupy the entire area of the parent RelativeLayout and be the same size regardless of the width of the screen.

In portrait mode I have 2 columns and in landscape - 3 cols.

 recyclerView.setHasFixedSize(true);
        int columns = resources.getConfiguration()
                .orientation == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2;

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), columns);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(columns,
                Utils.dpToPx(resources, 3), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(mLayoutManager);

How can I do that?


Solution

  • As always, after I write here a question, after a while the solution comes by itself. Here's how I solved this

    In your RecyclerView Adapter:

    @Override
    public HomeTilesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.home_tile_item, parent, false);
        int h = parent.getHeight();
        // margin - activity_vertical_margin
        // rows - number of rows in diffrent display modes
        h = (h - Math.round(margin*2))/rows;
    
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) itemView.getLayoutParams();
        params.height = h;
        itemView.setLayoutParams(params);
    
        return new MyViewHolder(itemView);
    }
    

    This decision solves the problem, but in the process I faced another problem. On the tablets the icon looks very small, it looks not beautiful. How I solved this issue you can read this post: ImageView size for phones and tablets

    Result

    enter image description here