Cannot resolve getSystemService method in ListView adapter

后端 未结 8 1517
深忆病人
深忆病人 2021-01-25 00:23

I am working through John Horton\'s Android Programming for Beginners, and am currently attempting to create a note-taking app. Horton has just introduced ListVie

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 00:42

    In my views, if you are learning then learn RecyclerView. bcz it is better than ListView. i am not saying that ListView has been depricated. But there alot of internal things in which RecyclerView is better.

    Following is example of Adapter

    public class NoteAdapter extends BaseAdapter {
    
        List mNoteList = new ArrayList();
    
        Context context;
    
        public NoteAdapter(Context context){
            this.context = context;
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    
        }
    
        @Override
        public int getCount(){
            return mNoteList.size();
        }
    
        @Override
        public Note getItem(int whichItem){
            return mNoteList.get(whichItem);
        }
    
        @Override
        public long getItemId(int whichItem){
            return whichItem;
        }
    
        @Override
        public View getView(int whichItem, View view, ViewGroup viewGroup){
    
            // check if view has been inflated already 
            if (view == null){
    
                view = inflater.inflate(R.layout.listitem, viewGroup, false);
    
            }
    
            return view;
        }
    
    } 
    

    Inside MainActivity.java

    NoteAdapter noteA = new NoteAdapter(MainActivity.this);
    

    OR

    NoteAdapter noteA = new NoteAdapter(getContext());
    

    OR

    NoteAdapter noteA = new NoteAdapter(getActivity);

    // if in Fragment

    OR

    NoteAdapter noteA = new NoteAdapter(getApplicationContext);

    // will work but no need to use it. bcz this is context of whole application. For an adapter you don't need context of whole application.

提交回复
热议问题