Android listFragment SetEmptyView 方法实现数据为空时的提示

我们知道在可以在ListFragment 中很方便的加载数据。因为Android为我们内置了一个listview,我们可以直接将数据绑定在上面。然而,当我们的应用中没有数据显示的时候,如何可以有效的提示用户或者让用户进行其他操作呢?

我们这里可以使用 setEmptyView(view)方法来实现。

具体代码如下

public class MylistFragment extends ListFragment{
    public View onCreatView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
        View view = super.onCreateView(inflater, container,
		 savedInstanceState);
        TextView emptyview = new TextView(getActivity());
        emptyview.setText("数据为空");
        ListView listview = (ListView)view.findViewById(android.R.id.list);
        listview.setEmptyView(emptyview);
    }
    
}

这里我动态创建了一个Textview 用来显示提示。然后使用Listview.setEmptyView(emptyview)方法绑定数据为空时的布局。运行后效果就有了。



但是我们有时候并不是仅仅只是提示用户而已,希望能有个丰富的界面来显示更多的内容。比如我们需要给用户一个按钮,让他进行其他操作。我们当然可以继续动态添加一个按钮,但是,我们有更好的方法,为什么不用呢?

因为我们继承的是ListFragment,所以,系统帮我们内置了ListView,当然我们也能使用自己的布局。

View view = inflater.inflate(R.layout.my_list, null, false);
用这句话替换super.onCreatView()方法。选择我们自己创建的布局文件。

my_list.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/crime_list_layout_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    

</FrameLayout>

然后,新建一个empty view empty_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:id="@+id/empty_layout">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="数据为空"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button_add_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加数据" 
        android:layout_marginTop="40dp"/>

</LinearLayout>



将建立好的empty_view 添加到当前布局

View emptyview = inflater.inflate(R.layout.empty_view, null, false);



设置按钮的单击事件

Button addDataButton = (Button)emptyview.findViewById(R.id.add_data);


addDataButton.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

addData();\\添加数据的具体实现

}

});



至此,运行之后,如果没有数据,就会加载empty_view.xml中的内容了。

你可能感兴趣的:(Android listFragment SetEmptyView 方法实现数据为空时的提示)