我正在使用本教程制作gridview: https://developer.android.com/guide/topics/ui/layout/gridview.html
我已将mThumbIds从array
更改为List<Integer>
,并且我尝试使用通过Bundle从MainActivity传入dataGridFragment的数据初始化它,但它不起作用。如果我手动添加元素,它可以工作。我认为捆绑包来得太晚但不知道如何同步它。
public class GameFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sudoku_game_fragment,
container, false);
ImageAdapter adapter = new ImageAdapter(getActivity());
List<Integer> array ;
GridView gridview = (GridView) view.findViewById(R.id.gridview);
gridview.setAdapter(adapter);
if(getArguments() != null) {
array =getArguments().getIntegerArrayList("values");
adapter.mThumbIds.add(0, R.drawable.zero);
}
adapter.notifyDataSetChanged();
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public List<Integer> mThumbIds = new ArrayList<Integer>();
// public Integer[] mThumbIds;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.size();
}
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) {
// populateImages();
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(1, 1, 1, 1);
imageView.setImageResource(R.drawable.one);
} else {
imageView = (ImageView) convertView;
}
//imageView.setImageResource(R.drawable.two);
// Log.d("getView", String.valueOf(values[position]));
imageView.setImageResource(mThumbIds.get(position));
return imageView;
}
}