I\'m trying to implement a GridViewPager so I can switch between 2 unique views. So far I haven\'t been able to add any views at all. Below is my code
public
First of all - the following line is wrong:
gridViewPager.addView(inflater.inflate(R.layout.selector_generic, stub));
inflate(int resource, ViewGroup root)
with root!=null
is the same as
inflate(int resource, ViewGroup root, boolean attachToRoot)
with last argument as true
.
So according to the documentation it will inflate view from resource
and attach it to root -> then return a root.
this will try to attach newly inflated view to stub
, and then try to attach stub
(result from inflate()
with specified root
) to the gridViewPager
. But stub
already has a parent (it's already attached to the view hierarchy in your activity). So this is an explanation of stacktrace:)
Please note that you should NOT add views to gridViewPager
via .addView()
methods - you should do it via adapter instead and that line should be removed.
Here is simple implementation for GridPagerAdapter
;
private class MyGridViewPagerAdapter extends GridPagerAdapter {
@Override
public int getColumnCount(int arg0) {
return 2;
}
@Override
public int getRowCount() {
return 2;
}
@Override
protected Object instantiateItem(ViewGroup container, int row, int col) {
final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.grid_view_pager_item, container, false);
final TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(String.format("Page:\n%1$s, %2$s", row, col));
container.addView(view);
return view;
}
@Override
protected void destroyItem(ViewGroup container, int row, int col, Object view) {
container.removeView((View)view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
}
Content of grid_view_pager_item.xml
:
<FrameLayout 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:padding="10dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="center_vertical"
android:gravity="center"
android:background="#4400ff00"
android:textColor="#000000"
android:textSize="26sp"/>
</FrameLayout>
Here is a final result of 2x2 grid. Two screens are in still state and two are pictured during the pages being half-scrolled:)
This is just an example of using standard GridPagerAdapter
. If you want more advanced one, with usage of FragmentGridPagerAdapter
, CardFragments
and pages backgrounds - please see the GridViewPager
example located in platform samples:
{sdk_root}/samples/android-20/wearable/GridViewPager