Here is what I did and I'm happy to say that this worked for me. I too wanted a 2x2, 3x3 etc. grid of items to cover the entire screen. Gridlayouts do not adhere to the width of the screen. LinearLayouts kind of work but you cant use nested weights.
The best option for me was to use Fragments I used this tutorial to get started with what I wanted to do.
Here is some code:
Main Activity:
public class GridHolderActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_6);
}
}
activity_main_6 XML (inflates 3 fragments)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/frag1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
<fragment
android:id="@+id/frag2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
<fragment
android:id="@+id/frag3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".Grid.TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
Base fragment layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="match_parent">
<ImageQueue
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/img1"
android:layout_weight="1"/>
<ImageQueue
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/img2"
android:layout_weight="1"/>
</LinearLayout>
Fragment Class (only handles initialization of a custom view) inflates 2 tiles per fragment
public class TwoHorizontalGridFragment extends Fragment {
private View rootView;
private ImageQueue imageQueue1;
private ImageQueue imageQueue2;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
rootView = inflater.inflate(
R.layout.two_horiz, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
imageQueue1.updateFiles();
imageQueue2.updateFiles();
}
}
Thats it!
This is a weird work around to using nested weights, essentially. It gives me a perfect 2x3 grid that fills the entire screen of both my 10 inch tablet and my HTC droid DNA. Let me know how it goes for you!