繁体   English   中英

Android自定义SimpleAdapter

[英]Android custom SimpleAdapter

我正在尝试这个例子为ListView创建一个simpleAdapter。 所以,我创造了所有,但当我改变这一行

List<Movie> movies = getData2();
ListAdapter adapter = new MovieListAdapter(this, movies, android.R.layout.simple_list_item_2, new String[]{Movie.KEY_NAME, Movie.KEY_YEAR}, new int[]{android.R.id.text1, android.R.id.text2});

我收到了这个错误:

构造函数未定义

MovieListAdapter(ImdbApiActivity, List<Movie>, int, String[], int[])

这是同样的例子,我刚刚改变了汽车电影。 我知道这个例子是从2009年开始的,我的目标是2.1。 版本之间是否存在不兼容性或是否存在错误?

我的simpleadapter类看起来像这样:

public class MovieListAdapter extends SimpleAdapter {

    private List < Movie > movies;

    private int[] colors = new int[] {
        0x30ffffff, 0x30808080
    };

    @SuppressWarnings("unchecked")
    public MovieListAdapter(Context context, List <? extends Map < String, String >> movies,
        int resource,
        String[] from,
        int[] to) {
        super(context, movies, resource, from, to);
        this.movies = (List < Movie > ) movies;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);

        int colorPos = position % colors.length;
        view.setBackgroundColor(colors[colorPos]);
        return view;
    }
}

我错过了一个错误吗? 这是实现这一目标的“现代”方式吗?

编辑:更改上下文参数或列表都不适用于此示例。 我的Movie类从Hashmap扩展而来。 还有其他想法吗? 谢谢!

import java.util.HashMap;

public class Movie extends HashMap {

    public String year;
    public String name;
    public static String KEY_YEAR = "year";
    public static String KEY_NAME = "name";

    public Movie(String name, String year) {
        this.year = year;
        this.name = name;
    }

    @Override
    public String get(Object k) {
        String key = (String) k;
        if (KEY_YEAR.equals(key))
            return year;
        else if (KEY_NAME.equals(key))
            return name;
        return null;
    }
}

它似乎是自定义适配器类构造函数的参数中的问题。

您已将其定义为List<? extends Map<String, String>> List<? extends Map<String, String>>电影,你从活动中传递List<Movies>对象。这就是它告诉你的原因,没有定义这样的构造函数。

尝试将constuctor的参数更改为List<Movies> movies ,这可以解决您的问题,我想!

尝试改变

`ListAdapter adapter = new MovieListAdapter(this, movies, android.R.layout.simple_list_item_2, new String[]{Movie.KEY_NAME, Movie.KEY_YEAR}, new int[]{android.R.id.text1, android.R.id.text2});`

`ListAdapter adapter = new MovieListAdapter(YourClass.this, movies, android.R.layout.simple_list_item_2, new String[]{Movie.KEY_NAME, Movie.KEY_YEAR}, new int[]{android.R.id.text1, android.R.id.text2});`

因为this可能是引用不同的实例。

YourClass.this是对YourClass.class实例的引用。 您还可以发送getApplicationContext()返回的上下文

暂无
暂无

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

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