如何用ListView替换表格布局

时间:2014-10-09 07:58:07

标签: android listview android-listview

我正在开发一个Android应用程序,我想要做的是用ListView替换Table布局。

实际上我使用Table和Scrollable Layout来显示列表等信息,我的数据包含在XML文件中,我用XMLpullparser解析,数据保存在数组列表中。

我的数组由“类别名称”(例如FOODS)和“项目名称”(例如披萨,maccheroni,鱼,筹码)组成,我想在此模式下显示此数据:

类别名称

列出项目

类别名称

列出项目

类别名称

列出项目

重要提示:每个数据必须具有细节样式,(类别名称必须具有特定的背景颜色,字体大小,字体颜色ecc和列表项必须具有某种样式)。

使用表格布局我有这个结果,因为我的表格的每一行都有不同的风格,但我怎么能用listview做到这一点?

这是我的xml

的一个小例子
<data>
  <category_name name="FOODS">
   <item item_name="pizza"></item>      
   <item item_name="pasta"></item>            
   </category>        
</data>

使用pullparser我将数据保存在数组中

1 个答案:

答案 0 :(得分:0)

如果您创建自己的模型类,具有属性类别,其构造函数及其getter和settes,如:

public class Food {

private String category;

public Food(String category) {
    super();
    this.category = category;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

}

之后,在主代码中将所有元素放在ArrayList中:

final ArrayList<Food> elements = new ArrayList<Food>();

    elements.add(new Food("pizza"));
    elements.add(new Food("pasta"));

    final FoodAdapter adapter = new FoodAdapter(this, 0, elements);
    listView.setAdapter(adapter);

然后制作自定义适配器:

public class FoodAdapter extends ArrayAdapter<Food> {

private ArrayList<Food> elements;

public FoodAdapter(Context context, int resource, ArrayList<Food> objects) {
    super(context, resource, objects);
    this.elements = objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if(elements.get(position).getCategory().equals("pizza")){
        convertView.setBackgroundColor(0xFF0000);
    }else if(elements.get(position).getCategory().equals("pasta")){
        convertView.setBackgroundColor(0x0000FF);
    }

    return super.getView(position, convertView, parent);
}

}

如果您遵循该代码,披萨元素将具有红色背景,而意大利面将是蓝色。