Search code examples
androidviewandroid-gridviewdynamically-generatedandroid-gridlayout

Different Cell size grid for custom views


I'm working on a project where I need to implement a grid to display "Widgets" (Custom made Views), reordered dynamically by the final user. More or less the same as Android Launchers and their widgets, Widgets that can be moved through the grid by the user (With long press, like most Launchers). Here is a preview of what I'm looking for: Every color represents one different kind of "Widget"

I've tried with GridLayout and TableLayout, but I'm not able to "merge" cells to adjust the layout to the Widget.

The grid itself is an 8 x 12 cells grid, where Widgets can use more than 1 cell each, for example, I've configured a "Widget button" that is 2 x 3 (h | w).

Is there any layout that fits what I need or I must create my own one?

Thank you, Abel!


Solution

  • I used the following code to programmatically create views and set up their PercentRelativeLayout.LayoutParams :

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_percent_relative);
    
        ViewGroup root = (ViewGroup)findViewById(R.id.perecent_layout_view);
    
        View blueWidget = new View(this);
        blueWidget.setBackground(blue);
        root.addView(blueWidget);
    
        setUpLayout(blueWidget, 2.0f/8.0f, 6.0f/8.0f, 6.0f/8.0f, 0.0f, 2.0f/8.0f, 0.0f);
    
        View redWidget = new View(this);
        redWidget.setBackground(red);
        root.addView(redWidget);
    
        setUpLayout(redWidget, 5.0f/8.0f, 2.0f/8.0f, 3.0f/8.0f, 0.0f, 0.0f, 6.0f/8.0f);
    
    }
    
    private void setUpLayout(View view, float widthPercent, 
                             float heightPercent,
                             float leftMarginPercent, 
                             float rightMarginPercent,
                             float topMarginPercent, 
                             float bottomMarginPercent) {
    
        PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(view.getLayoutParams());
        PercentLayoutHelper.PercentLayoutInfo percentLayoutInfo = layoutParams.getPercentLayoutInfo();
    
        percentLayoutInfo.heightPercent = heightPercent;
        percentLayoutInfo.widthPercent = widthPercent;
        percentLayoutInfo.topMarginPercent= topMarginPercent;
        percentLayoutInfo.bottomMarginPercent= bottomMarginPercent;
        percentLayoutInfo.leftMarginPercent= leftMarginPercent;
        percentLayoutInfo.rightMarginPercent= rightMarginPercent;
    
        view.setLayoutParams(layoutParams);
    
    }
    

    The view looks like this: enter image description here