我想在片段中创建按钮的gridview。我很困惑在我的代码中将什么作为参数传递给setAdapter,因为我尝试了getActivity和getContext时需要setAdapter函数的上下文。但无济于事。我引用的代码是针对Activity的,而不是针对片段的,因此它们通过了getActivity。
public class ExploreHabitFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_exloprehabit, container, false);
GridView gridView = view.findViewById(R.id.mygridview);
gridView.setAdapter(new ImageAdapter());
return view;
}
}
class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
private Integer[] mThumbIds = {
R.drawable.bitingnail , R.drawable.diet ,
R.drawable.gym , R.drawable.jogging ,
R.drawable.meditate , R.drawable.smoking ,
R.drawable.study , R.drawable.water ,
};
// Constructor
ImageAdapter(Context c){
mContext = c;
}
@Override
public int getCount() {
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
return mThumbIds[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
在传递getActivity时,会给出运行时错误并停止应用程序。 “这”行不通。