使用带有自定义适配器的字符串数组到listview?

时间:2016-07-15 16:41:08

标签: android listview custom-adapter

所以我有一个字符串数组。我试图将每个单独的项目从该字符串数组传递到自定义适配器。我无法弄清楚如何使用我在自定义适配器中传递的字符串?

我传递的字符串[]

 String favorites = String.valueOf(FavList.get(0).get("favorites_list"));

                String[] separated = favorites.split(",");

                for (String s: separated) {
                    //Do your stuff here
                    FavoritesAdapter.add(s);
                }

Adapter.class

public class FavoritesAdapter extends ArrayAdapter<favoriteList> {
private final Context mContext;
private List<favoriteList> favlist;
private TextView favorites;
private TextView favDetail;

public FavoritesAdapter(Context context, ArrayList<favoriteList> objects) {
    super(context, R.layout.favorites_listview_single, objects);
    this.mContext = context;
    this.favlist = objects;
}


public View getView(final int position, View convertView, final ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
        convertView = mLayoutInflater.inflate(R.layout.favorites_listview_single, null);
    }


   // Here is where i cant figure out how to get the string that I passed.






    return convertView;
}

}

2 个答案:

答案 0 :(得分:1)

看起来你只是在传递字符串,所以我不确定你为什么使用ArrayAdapter<favoriteList>

如果您将适配器类更改为:

public class FavoritesAdapter extends ArrayAdapter<String> {
    private final Context mContext;
    private ArrayList<String> favlist;
    private TextView favorites;
    private TextView favDetail;

    public FavoritesAdapter(Context context, ArrayList<String> objects) {
        super(context, R.layout.favorites_listview_single, objects);
        this.mContext = context;
        this.favlist = objects;
    }

    public View getView(final int position, View convertView, final ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
            convertView = mLayoutInflater.inflate(R.layout.favorites_listview_single, null);
        }

        String favoriteItem = favlist.get(position) //get the string you passed 


        return convertView;
    }

    //...more code
}

然后当你传递字符串时,传递它:

String favorites = String.valueOf(FavList.get(0).get("favorites_list"));
ArrayList<String> favlist = (ArrayList<String>)Arrays.asList(favorites.split(","));

FavoritesAdapter adapter = new FavoritesAdapter(getApplicationContext(), favlist);
listView.setAdapter(adapter); //where listView is the view you declared previously

答案 1 :(得分:0)

我不知道你是如何编写'FavoritesAdapter'类的,但是使用静态方法'add'并将字符串传递给它来构建列表感觉非常错误。

您可以通过此链接https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView了解如何创建如何为ListView创建自定义数组适配器