通過實現ViewPager並創建自己的PagerAdpter,我設法創建了一個儀表板,類似於一些設備的默認啓動器。請參見下面的代碼:
public class DashboardPagerAdapter extends PagerAdapter {
private static final int ROWS = 4;
private static final int COLS = 4;
private Context mContext;
private List<AppEntry> mData;
public DashboardPagerAdapter(Context context, List<AppEntry> data) {
mContext = context;
mData = data;
}
@Override
public int getCount() {
double ratio = (double) mData.size()/(ROWS * COLS);
return (int) Math.ceil(ratio);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TableLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
int cols = COLS, rows = ROWS;
switch (mContext.getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_PORTRAIT:
rows++;
break;
default:
cols++;
}
TableLayout table = new TableLayout(mContext);
table.setStretchAllColumns(true);
table.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
table.setBackgroundColor(Color.DKGRAY);
int start = position * rows * cols;
int end = Math.min(start + rows * cols, mData.size());
LayoutInflater inflater = LayoutInflater.from(mContext);
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(mContext);
row.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
row.setGravity(Gravity.CENTER);
for (int j = 0; j < cols; j++) {
int pos = start + i * cols + j;
if (pos < end) {
AppEntry item = mData.get(pos);
View vItem = inflater.inflate(R.layout.grid_item, null,
false);
ImageView image = (ImageView) vItem.findViewById(R.id.icon);
image.setImageDrawable(item.getIcon());
row.addView(vItem);
} else {
TextView vPlaceHolder = new TextView(mContext);
vPlaceHolder.setText(" ");
row.addView(vPlaceHolder);
}
}
table.addView(row);
}
container.addView(table);
return table;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
的instantiateItem方法,在這種情況下,返回一個TableLayout我使用來顯示應用程序圖標。我通過將數據集合的大小除以每頁的項目數(rows * cols)來計算頁面數(getCount())。
如果您想處理該事件,您可以在for循環內添加onClickListener到vItem。我建議在採取任何行動之前分享視圖之間的監聽者並要求標籤或ID。
如果您的內容是靜態的,您可能需要改爲使用FragmentPagerAdapter,併爲每個頁面創建一個Fragment。