简体   繁体   English

片段内的自定义列表适配器实例化

[英]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. 无法访问封闭类型的MainActivity。 Must qualify the allocation with an inclosing instance of type MainActivity. 必须使用类型为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 使您的ProverbAdapter静态: private static class ProverbAdapter
  2. Instantiate your ProverbAdapter inside an instance of MainActivity. 在MainActivity实例中实例化ProverbAdapter。

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() . 如果你将ProverbAdapter设为静态,你将在getLayoutInflater()上出错。 Static inner classes cannot access methods or variables from the outer class. 静态内部类不能从外部类访问方法或变量。 You could solve this particular problem by calling LayoutInflater.from(getContext()); 您可以通过调用LayoutInflater.from(getContext());来解决这个特殊问题LayoutInflater.from(getContext()); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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