4

我正在尝试填充一个列表视图,其中每行有 2 个文本视图和一个按钮。我想我几乎让它正常工作,但现在 ListView 只在 ListView 中显示 1 项并忽略其他数据。我还有 2 个 xml 文件(shelfrow.xml(2 个文本字段,1 个按钮)和 shelflist.xml(包含列表视图))。这是我的 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;
}
4

1 回答 1

9

这是因为您View在创建Adapter. 由于您只创建Adapter一次,因此您只膨胀一个View。AView需要为您的ListView.

而不是将 inflated 传递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);
    }
    ...
}
于 2011-05-21T23:02:20.837 回答