我为我的侄子制作了一个简单的卡片匹配游戏,创建了一个缩放,均匀间隔的gridview布局。它的表现非常符合我的要求,但似乎应该有一种不太复杂的方式来实现这一目标,所以我想知道是否有人能提出更好/更简单的方法。我是Android的新手,所以我可能过度设计了这个。
我有一个控制卡片数量(12-32)的设置,它可以缩放到任何尺寸的屏幕(各种尺寸和分辨率的平板电脑或手机)。
这是我的gridview XML:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:background="@drawable/wood"
android:layout_below="@id/score_board"
android:layout_above="@+id/messageparent"
/>
我有一个BaseAdapter的ImageAdapter子类,其getView看起来像这样。 getCellWidth和getCellHeight函数返回我在布局更改主活动中设置的值(见下文)。
public View getView(int position, View convertView, ViewGroup parent) {
CardView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new CardView(mContext,position,mCardFaces[position]); //mThumbIds[position]
imageView.setLayoutParams(new GridView.LayoutParams(((MainActivity)mContext).getCellWidth(), ((MainActivity)mContext).getCellHeight()));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//imageView.setPadding(R.dimen.card_padding, R.dimen.card_padding, R.dimen.card_padding, R.dimen.card_padding);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageResource(CardView.CARDBACK);
} else {
imageView = (CardView) convertView;
//If we recycle an old view, make sure it resizes appropriately
if (imageView.getWidth() != ((MainActivity)mContext).getCellWidth()) {
imageView.setLayoutParams(new GridView.LayoutParams(((MainActivity)mContext).getCellWidth(), ((MainActivity)mContext).getCellHeight()));
}
if(!mCardFaces[position].equals(imageView.getResID()))
imageView.updateCard(mCardFaces[position]);
}
return imageView;
}
这是我的sizeCardsToFit方法中的相关代码:
//... algorithm to calc cols, width and height to fit screen
gridview.setNumColumns(nCols);
gridview.setColumnWidth(width);
for (int i = 0; i < gridview.getChildCount(); i++) {
((CardView)gridview.getChildAt(i)).setLayoutParams(new GridView.LayoutParams(width,height));
}
mCellHeight=height;
mCellWidth=width;
答案 0 :(得分:0)
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MyGrid" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:padding="0dp"
android:verticalSpacing="2dp" android:horizontalSpacing="2dp"
android:scrollingCache="true" android:smoothScrollbar="true"
android:clipChildren="true" android:alwaysDrawnWithCache="true"
android:numColumns="auto_fit" android:columnWidth="100dp"
android:stretchMode="columnWidth" android:gravity="center_horizontal"
android:background="#000000">
</GridView>