Android ListView addHeaderView() nullPointerException for predefined Views defined in XML

前端 未结 1 1408
面向向阳花
面向向阳花 2020-12-01 07:01

Trying to use addHeaderView() and addFooterView() for a ListView. If I try to use a View that I\'ve predefined in XML for either the

相关标签:
1条回答
  • 2020-12-01 07:11

    EDIT:

    you simply cannot do

    View header = findViewById(R.layout.headerView);
    lst.addHeaderView(header);
    

    This will NOT work because the view which is being passed in has to be inflated. In a nutshell when you do setContentView at the beginning of your activity the android framework automatically inflates the view and puts it to use. In order to inflate your header view, all you have to do is

    View header = (View)getLayoutInflater().inflate(R.layout.headerView,null);
    ls.addHeaderView(header);
    

    lastly, add your adapter after you’ve set the header view and run the application. You should see your header view with the content you put into your adapter.

    In my case, this works

    View header = getLayoutInflater().inflate(R.layout.header, null); 
    View footer = getLayoutInflater().inflate(R.layout.footer, null); 
    
    ListView listView = getListView();  
    
    listView.addHeaderView(header); 
    listView.addFooterView(footer);     
    
    setListAdapter(new ArrayAdapter<String(this,android.R.layout.simple_list_item_single_choice,android.R.id.text1, names)); 
    
    0 讨论(0)
提交回复
热议问题