簡體   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