问题
I have a ListFragment
and I want to set its empty view, so I use the following code:
View emptyView = getLayoutInflater().inflate(R.layout.collection_empty_view, null);
detailFragment.getListView().setEmptyView(emptyView);
for the following xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/empty_collection" />
<Button
android:id="@+id/btn_add_legislation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addText"
android:text="@string/action_add_text" />
</LinearLayout>
But nothing shows up!
I tried detailFragment.getListView().setEmptyText()
, and that did work! Am I doing domething wrong?
回答1:
The empty view has to be in the same view hierarchy as the list view. Inflating it that way won't work.
Generally I create a layout in the format below:
<Layout>
<ListView/>
<View android:id="@+id/empty"/>
</Layout>
Where empty view is the View I want to use as my "empty view". Then in on create I get a reference to the empty view and call setEmptyView() with that reference.
Here's an example from the Android documentation (check out the documentation, it should be applicable to SherlockListFragment):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="@id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
回答2:
You can try something which I'm doing in a fragment of my application. I don't know if it's a good practice but it works!
View emptyView = getActivity().getLayoutInflater().inflate(R.layout.empty, null);
getActivity().setContentView(emptyView);
来源:https://stackoverflow.com/questions/17472137/setemptyview-doesnt-seem-to-work-for-sherlocklistfragment