Android gridview in fragment adapter constructor missing

I am trying to implement an image grid. I did this in my work, referring to this link . Now, if I try to implement the same thing in a class that extends a fragment, I did this

package com.example.emergency1; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.GridView; public class City1 extends Fragment { public static Fragment newInstance(Context context) { City1 f = new City1(); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.city1, null); GridView gv1=(GridView)getView().findViewById(R.id.gridview); gv1.setAdapter(new ImageAdapter(this)); return root; } } 

and for the adapter

 package com.example.emergency1; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { private Context ctx; public ImageAdapter(Context c) { ctx=c; } @Override public int getCount() { // TODO Auto-generated method stub return pics.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ImageView iv; if (convertView == null) { // if it not recycled, initialize some attributes iv = new ImageView(ctx); iv.setLayoutParams(new GridView.LayoutParams(350,350)); iv.setScaleType(ImageView.ScaleType.CENTER_CROP); iv.setPadding(8, 8, 8, 8); } else { iv = (ImageView) convertView; } iv.setImageResource(pics[position]); return iv; } private Integer[] pics={ R.drawable.sample_0,R.drawable.sample_1, R.drawable.sample_2,R.drawable.sample_3, R.drawable.sample_4,R.drawable.sample_5, R.drawable.sample_6,R.drawable.sample_7 }; } 

Here I get an error in the line

gv1.setAdapter(new ImageAdapter(this));

Since I do not have a corresponding constructor in the adapter class. How to solve this problem. Could you also redirect me to some link where I can learn more about how to implement activity user interface elements in fragments? Thanks

+2
source share
1 answer

Using

  gv1.setAdapter(new ImageAdapter(getActivity())); 

instead of this

  gv1.setAdapter(new ImageAdapter(this)); 

You need to pass an activity context.

Also this

  GridView gv1=(GridView)getView().findViewById(R.id.gridview); 

it should be

  GridView gv1=(GridView)root.findViewById(R.id.gridview); 
+4
source

Source: https://habr.com/ru/post/955380/


All Articles