简体   繁体   中英

Custom List Adapter Instantiation Within Fragment

I'm trying to instantiate a custom list adapter.

The Adapter:

private class ProverbAdapter extends ArrayAdapter<String> {
    public ProverbAdapter(Context context, int layout, int resId, String[] items) {
        super(context, layout, resId, items);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        if(row == null) {
            row = getLayoutInflater().inflate(R.layout.proverb_layout, parent, false);
        }

        String item = getItem(position);

        return row;
    }
}

Instantiation

Context c = getActivity().getApplicationContext();
ProverbAdapter adapter = new ProverbAdapter(c,R.layout.proverb_layout,R.id.proverb_content,all_proverbs);

I'm getting an error from the compiler that says

No enclosing type of MainActivity is accessible. Must qualify the allocation with an inclosing instance of type MainActivity.

I'm not really sure what I'm doing wrong here. It seems like passing the fragment context in should be enough.

You have two options:

  1. Make your ProverbAdapter static: private static class ProverbAdapter
  2. Instantiate your ProverbAdapter inside an instance of MainActivity.

This is due to the fact that non-static inner classes have a reference to an instance of their outer class so you can easily access methods and variables of that outer class. If you don't instantiate the innerclass inside an instance of the outer class, there is no reference available to that outer class.


If you make the ProverbAdapter static, you will get an error on getLayoutInflater() . Static inner classes cannot access methods or variables from the outer class. You could solve this particular problem by calling LayoutInflater.from(getContext()); .

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