gpt4 book ai didi

java - 代码较短,因此用相同的值填充数组

转载 作者:行者123 更新时间:2023-12-01 11:25:43 25 4
gpt4 key购买 nike

对于我的“内存”游戏,我使用 GridView 来显示 12 张卡片。
一开始,牌都是一样的。

在我找到的所有示例中,您都会看到类似于此代码的内容,用于将图片 id 添加到 ImageAdapter:

 private Integer[] mThumbIds = {     
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back
};

有没有更短、更干净、更好的方法?像这样的东西:

private Integer[] mThumbIds = new Integer[11];
Arrays.fill(mThumbIds, R.drawable.card_back);

全类:

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import java.util.Arrays;

public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context c) {
mContext = c;
}

public int getCount() {
return mThumbIds.length;
}

public Object getItem(int position) {
return null;
}

public long getItemId(int position) {
return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}

imageView.setImageResource(mThumbIds[position]);
return imageView;
}

// references to our images

Integer[] mThumbIds = new Integer[11];
Arrays.fill(mThumbIds, R.drawable.card_back);


/* R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back,
R.drawable.card_back, R.drawable.card_back
};*/

}

最佳答案

实际上,就是这样 - 您可以使用 java.util.Arrays#fill :

Arrays.fill(mThumbIds, R.drawable.card_back);

关于java - 代码较短,因此用相同的值填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30816368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com