【问题标题】:Using ArrayListAdapter with ListView将 ArrayListAdapter 与 ListView 一起使用
【发布时间】:2011-03-31 01:39:12
【问题描述】:

我正在使用自定义 ArrayAdapter 来在我的页面中填充 ListView。这是该适配器的启动代码:

public IngredientListAdapter(Context context, int layout_resourceid, ArrayList<RecipeItem> items) {
    super(context, layout_resourceid);
    this.items = items ;
    ctx = context;
}

对于这个数组适配器,我传递一个 RecipeItems 数组(在我的 ListRecipeItems ListActivity 类中):

iAd = new IngredientListAdapter(this, R.layout.recipeitem_row, recipe.Ingredients );              
     this.setListAdapter(iAd) ;

然而,我发现 ListView 没有被填充,尽管 recipe.Ingredients ArrayList 肯定被正确填充。

检查 iAd.items.getCount() 确认项目在那里。 我可以让 ListView 填充的唯一方法是使用 .add() 例如手动将每个项目添加到其中;

for(int i=0;i<recipe.Ingredients.size();i++)
{ 
  iAd.add(recipe.Ingredients.get(i)); 
}

我的理解是,在初始化时将完整数组传递给 ArrayAdapter 会自动填充该 ListView。然而,似乎从未调用过 Adapater 的 getView 方法。

有人能解释一下这种行为吗?我对 android 和 java 还很陌生,所以我可能错过了一些明显的东西。

非常感谢 尼克

【问题讨论】:

    标签: android listview android-widget


    【解决方案1】:

    看起来您没有将您的项目传递给超类,因此 ArrayAdapter 对您的项目集合一无所知。在调用超类构造函数时尝试将项目作为第三个参数传递:

    super(context, layout_resourceid, items);
    

    【讨论】:

    • 太棒了,行得通!我知道我错过了一些简单的事情。谢谢丹 :)
    【解决方案2】:

    如果我在设置适配器时传递了一个 ArrayList,它也不会填充。我今天早上正在处理这个问题。如果我只是传入一个空的 ArrayList,那么就做

    iAd.add(object); 
    

    然后调用

    iAd.notifyDataSetChanged();
    

    项目将显示出来。

    【讨论】:

    • 你好安德鲁。丹的解决方案对我有用(见上文)。我没有将数组传递给超级构造函数。这也可能是你的问题?
    • 不,我将数组传递给超级构造函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多