Usersadapter中的UsersAdapter无法应用于(...)

时间:2016-06-26 07:22:43

标签: android android-arrayadapter

我正在尝试学习在ListView中显示一系列文章链接。尝试创建适配器以将数组项转换为视图时,我收到此错误消息。

Error:(62, 36) error: constructor UsersAdapter in class 
    HovedSide.UsersAdapter cannot be applied to given types;
    required: Context,ArrayList<HovedSide.User>
    found: HovedSide.UsersAdapter,ArrayList<HovedSide.User>
    reason: actual argument HovedSide.UsersAdapter cannot be
    converted to Context by method invocation conversion

源代码:

public class HovedSide extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hoved_side);
    }

    public class User {
        public String article;

        public User(String article) {
            this.article = article;
        }
    }
    public class UsersAdapter extends ArrayAdapter<User> {
        public UsersAdapter(Context context, ArrayList<User> users) {
            super(context, 0, users);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            User user = getItem(position);
            view
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.items_list, parent, false);
            }
            TextView articlename = (TextView) convertView.findViewById(R.id.tvarticle);
            articlename.setText(user.article);          
            return convertView;

            ArrayList<User> arrayOfUsers = new ArrayList<User>();
            UsersAdapter adapter = new UsersAdapter(this,arrayOfUsers);
            ListView listView = (ListView) findViewById(R.id.listView);
            listView.setAdapter(adapter);
            User newUser = new User("Article1");
            adapter.add(newUser);
        }
    }
}

错误:

UsersAdapter adapter = new UsersAdapter(this,arrayOfUsers);

尝试将其替换为以下内容,如其他帖子所示;

UsersAdapter adapter = new UsersAdapter(getActivity(),arrayOfUsers);

1 个答案:

答案 0 :(得分:1)

我在Activty中测试你的代码并且工作正常。 在nil中你必须使用这样的东西:

AppCompatActivity

更新

我在v7中尝试过,这也很好。这是我的代码

getApplicationContext()