我已按照有关如何使用GridView的文档进行操作,并遇到与此人ImageAdapter cannot be applied to a Fragment Class
相同的问题我的片段类中的代码如下
public class SecondFragment extends Fragment {
View myView;
GridView gridview;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.second_layout, container, false);
gridview = (GridView) myView.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(getActivity()));
return myView;
}
}
但是我在倒数第二行出现错误“Image Adapter无法应用于android.app.activity”
我的ImageAdapter如下
public class ImageAdapter extends BaseAdapter {
private Context mcontext;
@Override
public int getCount() {
return mthumbids.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mcontext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView)convertView;
}
return imageView;
}
private Integer[] mthumbids =
{
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6
};
}
答案 0 :(得分:0)
在ImageAdapter类中添加此代码。
{{1}}
答案 1 :(得分:0)
您还可以从USER_ID
中的父级获取上下文。然后,您不必传递和存储上下文。所以你的getView()
看起来像这样:
getView
答案 2 :(得分:0)
缺少ImageAdapter的参数上下文的构造函数。 只会自动创建空构造函数 你应该编写具有特定参数值的构造函数。
public ImageAdapter(Context context){
mContext = context; }
答案 3 :(得分:0)
你需要在ImageAdapter
类中有一个构造函数,它将上下文作为参数。
您还必须根据适配器位置设置图像的背景。
这是修改后的适配器类。
public class ImageAdapter extends BaseAdapter {
private Context mcontext;
public ImageAdapter (Context context) {
mContext = context;
}
@Override
public int getCount() {
return mthumbids.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mcontext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
// Add the following to load the image
imageView.setBackground(ContextCompat.getDrawable(context, mthumbids[position]));
}
else {
imageView = (ImageView)convertView;
}
return imageView;
}
private Integer[] mthumbids =
{
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6
};
}