Android - Inflating ListView

Plo*_*oon 4 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); 
Run Code Online (Sandbox Code Playgroud)

和我的类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;
}
Run Code Online (Sandbox Code Playgroud)

Gya*_*uyn 9

这是因为你View在创建时充气Adapter.由于您只创建Adapter一次,因此您只需要一次充气View.一个View需要被夸大为你的每一个可见行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;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

你这个:

// 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);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)