Want to setEmptyView() of a ListActivity

2019-03-02 13:19发布

As the title suggests, I want to set a default view for a list activity. I have tried to do this :

TextView emptyView = new TextView(this);
emptyView.setText("No lists available");
this.getListView().setEmptyView(emptyView);

But this did not work.

1条回答
爷、活的狠高调
2楼-- · 2019-03-02 14:06

The problem is that emptyView is never attached to anything, if you use addView():

TextView emptyView = new TextView(this);
((ViewGroup) getListView().getParent()).addView(emptyView);
emptyView.setText("It's empty!");
getListView().setEmptyView(emptyView);

Now you'll see it!


I wrote a quick Runnable to alternate between empty / "full"...

public class Example extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView emptyView = new TextView(this);
        ((ViewGroup) getListView().getParent()).addView(emptyView);
        emptyView.setText("It's empty!");
        getListView().setEmptyView(emptyView);

        getListView().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(getListAdapter() == null)
                    setListAdapter(new ArrayAdapter<String>(Example.this, android.R.layout.simple_list_item_1, new String[] {"It", "Has", "Content"}));
                else
                    setListAdapter(null);
                getListView().postDelayed(this, 2000);
            }
        }, 2000);
    }
}
查看更多
登录 后发表回答