Make the GridView column and column widths adaptive when the Android phone rotates the screen

Source: Internet
Author: User

Inadvertently opened a year ago to do an Android app code, see the implementation of a small function point (such as the title), now write an article to make a note. The problem was that when rotating the screen, the number of columns and widths of the GridView were adapted to the width of the screen, and a certain amount of space was required between each cell. Because each phone's screen width is not the same, we have specified the width and spacing of the cell, and cannot determine the number of cells in each row can accommodate, this number must be calculated at run time, similarly, we set the cell width and spacing is not guaranteed to fit exactly within the screen width, in order to solve this problem, Design a simple algorithm, first need to specify the width and spacing of the cell, and then based on the screen width by calculating the adjusted cell width and the number of cells per row can be accommodated, for each cell, the adjusted width and initial width of the error is less than: cell initial width/(2 * The number of cells per row after adjustment, the maximum error in extreme cases when the cell width is less than the width of the screen: cell initial width/4. After the experiment, it solves the problem of self-adapting very well.

The algorithm flow is as follows:

    1. Specifies the cell initial width value width and spacing padding, and gets the screen width value
    2. Calculate whether the screen is just enough to hold the entire number of cells, if you can, calculate the number of cells, and then jump directly to the 6th step, otherwise continue the next
    3. Calculates the total width of the cell beyond the width of the screen, and if the value exceeds half the value of the initial width of the cell, continue to the next step, or skip to 5th
    4. Calculate the number of cells and divide the width of the screen by the number of cells (negative values) to each cell, that is: Cellwidth = Cellwidth-avgspace, and then skip to step 6th
    5. Count the number of cells and subtract the cell width from the width of the screen by dividing it by the number of cells (positive value) and adding to each cell, that is: Cellwidth = cellwidth + avgspace
    6. Calculates the total spacing based on the number of cells, and adds the total spacing (negative values) to each cell, that is: Cellwidth = cellwidth-avgpadding
    7. Finally, the number and width of adaptive cells are obtained.

This allows us to implement a small algorithm, by specifying the column spacing (which does not need to be set to 0) and the initial column width (this value is only a approximate width), can be at run time according to the width of the phone screen to automatically calculate the screen can accommodate the exact column width and number of columns, so as to block the number of mobile phone screen size For adaptive purposes, this method can also be applied to other similar scenarios.

Sketch when analyzing a problem:

① is more than half the width of the screen than the initial width of the cell, corresponding to the 3rd, 4, 6 steps of the algorithm flow

② is more than half the width of the screen than the initial width of the cell, corresponding to the 3rd, 5, 6 steps of the algorithm flow

Place the code that calculates the cell width in the Oncreateview method so that the number of cells and the width of each row in the GridView is automatically adjusted each time you rotate the screen so that it fits exactly within the screen width.

Here is the run (look closely at the width of the cells in the vertical screen and the horizontal screen is not the same, adaptive results):

The code is as follows (some unnecessary code is omitted):

 Public classFragmentallbushouextendsFragment {GridView GridView=NULL; @Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {WindowManager Mang ER=getactivity (). Getwindowmanager (); Display Display=Manager.getdefaultdisplay (); //Screen Height        intScreenHeight =display.getheight (); //Screen Width        intScreenWidth =display.getwidth (); GridView=NewGridView (Getactivity ()); columninfo colinfo = Calculatecolumnwidthandcountinrow (screenwidth, 100,2); intRowNum = Cursor.getcount ()%colinfo.countinrow = = 0? Cursor.getcount ()/colinfo.countinrow:cursor.getcount ()/colinfo.countinrow+1; Gridview.setlayoutparams (NewLayoutparams (screenwidth,rownum*colinfo.width+ (rowNum-1) * *));        gridview.setnumcolumns (colinfo.countinrow);        Gridview.setgravity (Gravity.center); Gridview.sethorizontalspacing (2); Gridview.setverticalspacing (2);    Gridview.setstretchmode (Gridview.stretch_column_width); }    //Store calculated cell-related information    classcolumninfo{//Cell Width         Public intwidth = 0; //the number of cells that can be accommodated per row         Public intCountinrow = 0; }              /*** Calculate the width of each cell of the GridView according to the screen width of the phone *@paramscreenwidth Screen Width *@paramWidth cell preset widths *@parampadding cell spacing *@return     */    PrivateColumninfo Calculatecolumnwidthandcountinrow (intScreenWidth,intWidthintpadding) {Columninfo Colinfo=NewColumninfo (); intColCount = 0; //Determine if the screen is just enough to hold the entire number of cells, and if not, save the extra width to space        intSpace = screenwidth%width; if(Space = = 0) {//just hold it down .ColCount = screenwidth/width; }Else if(Space >= (WIDTH/2)) {//when the extra width is greater than half the width of the cell, the last cell is stripped and the width is divided and added to each of the other cellsColCount = screenwidth/width; Space= width-space; Width= width + Space/ColCount; }Else{//when the extra width is less than half the width of the cell, the extra width is divided evenly, and each cell is subtracted from the width of the split.ColCount = screenwidth/width + 1; Width= Width-space/ColCount; } Colinfo.countinrow=ColCount; //calculates the total width of the spacing for each row and resizes the cell width according to the number of cellsColinfo.width = width-((colcount + 1) * padding)/ColCount; returnColinfo; }}

Make the GridView column and column widths Adaptive

when the Android phone rotates the screen

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.