Android - Inflating ListView

时间:2011-05-21 22:37:40

标签: android listview inflate

我正在尝试填充列表视图,其中每行有2个textviews和一个按钮。我认为我几乎可以正常工作但是现在ListView只显示ListView中的1个项目并忽略其他数据。我还有2个xml文件(shelfrow.xml(2个文本字段,1个按钮)和shelflist.xml(包含listview))。 这是我的Shelf.java类的核心代码。 (MyListItemModel是用于存储每本书的类)

List<MyItemModel> myListModel = new ArrayList<MyItemModel>();
try{
JSONArray entries = json.getJSONArray("entries");
for(int i=0;i<entries.length();i++){                        
     MyItemModel item = new MyItemModel();    
     JSONObject e = entries.getJSONObject(i);
     alKey.add(e.getInt("key")); 
     item.id = i;
     item.title = e.getString("title");
     item.description = e.getString("description");

      myListModel.add(item);
 }

}catch(JSONException e)        {
Log.e("log_tag", "Error parsing data "+e.toString());
}
//THIS IS THE PROBLEM I THINK - ERROR: The method inflate(int, ViewGroup) in the type LayoutInflater is not applicable for the arguments (int,Shelf)
MyListAdapter adapter = new MyListAdapter(getLayoutInflater().inflate(R.layout.shelfrow,this));

adapter.setModel(myListModel);
setListAdapter(adapter);
lv = getListView();
lv.setTextFilterEnabled(true); 

和我的班级MyListAdapter

中的一些代码
 @Override
  public View getView(int position, View convertView, ViewGroup parent) {

 if(convertView==null){
   convertView = renderer;

    }
    MyListItemModel item = items.get(position);
     // replace those R.ids by the ones inside your custom list_item layout.
     TextView label = (TextView)convertView.findViewById(R.id.item_title);
     label.setText(item.getTitle());
     TextView label2 = (TextView)convertView.findViewById(R.id.item_subtitle);
    label2.setText(item.getDescription());
    Button button = (Button)convertView.findViewById(R.id.btn_download);
    button.setOnClickListener(item.listener);
    //}
    return convertView;
}

1 个答案:

答案 0 :(得分:9)

这是因为您在创建View时夸大了Adapter。由于您只创建了一次Adapter,因此您只需要一个ViewView中的每个可见行都需要为ListView充气。

而不是将膨胀的View传递给MyListAdapter的构造函数:

MyListAdapter adapter = new MyListAdapter(getLayoutInflater().inflate(R.layout.shelfrow,this));

...

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

    if(convertView == null) {
        convertView = renderer;
    }
    ...
}

你的意思:

// Remove the constructor you created that takes a View.
MyListAdapter adapter = new MyListAdapter();

...

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

    if(convertView == null) {
        // Inflate a new View every time a new row requires one.
        convertView = LayoutInflater.from(context).inflate(R.layout.shelfrow, parent, false);
    }
    ...
}