简体   繁体   中英

Getting the correct context in an adapter and fragment

I am getting an error in my adaptor

Error:(26, 20) error: incompatible types: MainFragment cannot be converted to Activity

and I suspect that its because the type of context I am trying to use is for activities as opposed to fragments

the adaptor

public class CustomListAdapter extends ArrayAdapter<String> {

   private final Activity context;
   private final String[] itemname;
   private final Integer[] imgid;

   public CustomListAdapter(MainFragment context, String[] itemname, Integer[] imgid) {
      super(context, R.layout.mylist, itemname);
      // TODO Auto-generated constructor stub
      this.context=context;
      this.itemname=itemname;
      this.imgid=imgid;
   }

   public View getView(int position,View view,ViewGroup parent) {
      LayoutInflater inflater=context.getLayoutInflater();
      View rowView=inflater.inflate(R.layout.mylist, null,true);

      TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
      ImageView imageView = (ImageView) rowView.findViewById(R.id.icons);
      TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);

      txtTitle.setText(itemname[position]);
      imageView.setImageResource(imgid[position]);
      extratxt.setText("Description "+itemname[position]);
      return rowView;

   };
}

The Fragment

public class MainFragment extends Fragment {

    ListView list;
    String[] itemname ={
            "Safari",
            "Camera",
            "Global"
            /*"FireFox",
            "UC Browser",
            "Android Folder",
            "VLC Player",
            "Cold War"*/
    };

    Integer[] imgid={
            R.drawable.watersensoricon,
            R.drawable.ic_shutoff,
            R.drawable.ic_camera,

    };


    public MainFragment()
    {
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Bundle bundle = this.getArguments();
        //Integer data = EventBus.getDefault().removeStickyEvent(Integer.class);
        //if (data != null)
        //{
        //   classificationGroupFilter = data.intValue();
        //}

        // DashboardActivity activity = (DashboardActivity) getActivity();
        // int call = activity.openCallLogs();
        View view = inflater.inflate(R.layout.icons_main, container, false);
        //load(view);
        setupList(view);

        return view;
    }

//  @Override
private void setupList(View view){
        //super.onCreate(savedInstanceState);
        //setContentView(R.layout.icons_main);

        CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);
        list=(ListView)view.findViewById(R.id.list);
    //(ListView)view.findViewById(R.id.lv_listview);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                // TODO Auto-generated method stub
                String Slecteditem= itemname[+position];
                //Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();

            }
        });
    }
}

Layout For XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context ="com.xera.deviceinsight.home.MainFragment">
          <!--      tools:context="{relativePackage}.${activityClass}" >-->

   <ListView
      android:id="@+id/list"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true" >
   </ListView>

</RelativeLayout>

Change

CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);

To

CustomListAdapter adapter=new CustomListAdapter(getActivity(), itemname, imgid);

Because in your case this is link to MainFragment , not to Activity.

Adapter require context of an Activity . You can use getActivity() method of the fragment for accessing the Activity context. Mind you, you need to make sure that the fragment is attached to an Activity .

So to fix this replace following

CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);

with

CustomListAdapter adapter=new CustomListAdapter(getActivity(), itemname, imgid);

you can use

viewGroup.getContext()

in onCreateViewHolder, or

viewHolder.getView().getContext()

in onBindViewHolder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM