3

I have 4 buttons that I want to show in a gridview. I want them to fill the screen as much as possible, but I never made it. I've tried all kind of ScaleTypes and it won't work. Right now I have the scale type in FIT_CENTER but i get an unexpected result. Here's the code I have so far:

Main.java

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Display screenSize = getWindowManager().getDefaultDisplay();
        int screenWidth = screenSize.getWidth();
        int screenHeight = screenSize.getHeight();

        int iconWidth =  screenWidth/4;
        int iconHeight=  screenHeight/2;

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this, iconWidth, iconHeight));

        }

ImageAdapter.java

public View getView(final int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(m_Context);
            imageView.setLayoutParams(new GridView.LayoutParams(m_width, m_height));
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(8, 8, 8, 8);

        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

GridViewLayout.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:numColumns="2"
    android:background="#FFFFFF"/>

The result of the code looks like this:

wrong result

This is what i would like it to look like:

desired result

Note that the last screen shot is hard coded which is obviously not my wish. I want this to work in every screen size without hard coding.

Mirza Sisic
  • 2,401
  • 4
  • 24
  • 38
madcoderz
  • 4,423
  • 10
  • 47
  • 74
  • May be this can help you...But this has been done for a Linear Layout http://stackoverflow.com/questions/2581481/assign-width-to-half-available-screen-width-declaratively – DeRagan Feb 01 '11 at 11:30
  • the thing is that i'm using images, not only buttons, i've being struggling with this for a couple of days now and i find no way to make it work. I've gone from relative to linear layouts and table layouts and nothing happens, i can't nail it. – madcoderz Feb 01 '11 at 12:54

1 Answers1

0

You can achieve it using recycler view with GridLayoutManager. there you can define size of a single item to match half of device height and width. Then it'll be you expected result.

Manmohan Badaya
  • 2,326
  • 1
  • 22
  • 35