Android - Inflating ListView

前端 未结 1 735
醉酒成梦
醉酒成梦 2020-12-21 04:58

I am trying to populate a listview where each row has 2 textviews and a button. I think I nearly have it working properly but right now the ListView only shows 1 item in the

相关标签:
1条回答
  • 2020-12-21 05:21

    It is because you inflate the View when you create the Adapter. Since you only create the Adapter once, you only inflate one View. A View needs to be inflated for every visible row in your ListView.

    Instead of passing the inflated View to the constructor of 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;
        }
        ...
    }
    

    Thy this:

    // 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);
        }
        ...
    }
    
    0 讨论(0)
提交回复
热议问题