Android How to reuse a header layout as an empty view in a ListView

送分小仙女□ 提交于 2019-11-30 23:50:08

If you want to show the header of a ListView when the list is empty, what you really want to do is to show the list itself rather than a separate empty view. So, the simplest way is to check whether your list is empty and set the list visible if it is not already:

getListView().setVisibility(View.VISIBLE);

You can test this very easily with the following code:

public class TestListActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_listview);

        // create the empty grid item mapping
        String[] from = new String[] {};
        int[] to = new int[] {};

        // prepare the empty list
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

        // fill in the grid_item layout
        SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.test_listitem, from, to);

        View listHeader = 
                ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.test_listheader, null, false);

        getListView().addHeaderView(listHeader);
        getListView().setAdapter(adapter);
    }
}

The list is empty, but the header is visible.

My solution is to create a view with the layout for the header, but set the background to be the same as the list items. android:background="@android:drawable/list_selector_background"

But my solution does not work if I use 'include' to embed the header layout from another layout file. Do not know why.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!