当 ListView 为空时 Android 显示文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10017088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:12:17  来源:igfitidea点击:

Android displaying text when ListView is empty

androidandroid-listview

提问by Daniel

I'm setting a TextViewwith the id @android:id/emptyto display a message when there are no items in the ListView. However, this TextViewgets displayed even if there are items in the ListView, right before the items show up.

我正在设置TextView带有 id 的@android:id/emptya 以在ListView. 但是,TextView即使 , 中存在项目,也会ListView在项目出现之前显示。

How can I make it such that it only gets displayed when there are no elements in the ListView?

我怎样才能让它只在没有元素时显示ListView

<?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" >

<ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:dividerHeight="1dp" >
</ListView>

<TextView 
    android:id="@android:id/empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/empty_list" />

</LinearLayout>

PS: I'm using a Loaderand a SimpleCursorAdapterwith a ListFragment.

PS:我正在使用 aLoaderSimpleCursorAdaptera ListFragment

回答by dymmeh

I'm guessing you are using a regular Fragmentor Activitywith a ListViewinside of it. If you are, you must add the empty layout to the ListViewmanually.

我猜你是使用常规FragmentActivityListView它的内部。如果是,则必须ListView手动添加空布局。

E.g.

例如

ListView lv = (ListView)findViewById(android.R.id.list);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
lv.setEmptyView(emptyText);

Then your ListViewwill automatically use this view when its adapter is empty

然后ListView当它的适配器为空时你会自动使用这个视图

If you are using a ListActivityyou do not need to call setEmptyView()on the ListViewsince the ListActivityautomatically manages that for you.

如果您使用的是 a ListActivity,则不需要调用setEmptyView()ListView因为它会ListActivity自动为您管理。

回答by CoderDecoder

Set a TextViewand assign to it whatever you want to display when the ListViewis empty:

设置 aTextView并将其分配给ListView空时要显示的任何内容:

ProjectListAdapter projectListAdapter = new ProjectListAdapter();
TextView empty=(TextView)findViewById(R.id.empty);
projectsListView.setEmptyView(empty);

And in my xml file we write the below code

在我的 xml 文件中,我们编写了以下代码

<TextView
      android:id="@+id/empty"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:gravity="center"
      android:text="Your text here"
      android:textColor="#FFFFFF" />

回答by CircuitBreaker716

I had this problem. You have to set the emptyView explicitly in your code.

我有这个问题。您必须在代码中明确设置 emptyView。

Change your TextView:

改变你的TextView

<TextView 
    android:id="@+id/emptyResults"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/empty_list" />

Then in the onCreate():

然后在onCreate()

listViewResults = (ListView) findViewById(R.id.list);
listViewResults.setEmptyView((LinearLayout) findViewById(R.id.emptyResults)); 

This code above assumes your ListViewis in a LinearLayout.

上面的代码假设您ListViewLinearLayout.

回答by v1k

I used ListFragmentand had the same issue. I tried all variants from this answers, but the problem wasn't solved.

我使用过ListFragment并遇到了同样的问题。我尝试了这个答案的所有变体,但问题没有解决。

So I found my variant, to override setEmptyText():

所以我找到了我的变体,以覆盖setEmptyText()

public class NewsFragment extends ListFragment{
    private TextView emptyText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        //...

        emptyText = (TextView)view.findViewById(android.R.id.empty);

        //...
    }

    @Override
    public void setEmptyText(CharSequence text) {
        emptyText.setText(text);
    }
}

Hope it will be helpful for somebody.

希望它会对某人有所帮助。

回答by Lena Bru

I know this is kind of late, but for it to work from XML, you need to put a weight on your ListViewand have your TextViewmatch_parent

我知道这有点晚了,但是要使其从 XML 工作,您需要对自己施加压力ListView并让TextViewmatch_parent

<?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" >

<ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:dividerHeight="1dp" >
</ListView>

<TextView 
    android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/empty_list" />

</LinearLayout>

回答by Alex Jolig

There's a good exampleof how to do it which works awesome:

有一个很好的例子说明如何做到这一点,效果很棒:

When you want to show a message to the user when the ListViewis empty, you have to keep in mind the following 3 steps:

  • In the xml where the ListViewis declared, create a TextView(the TextView can be inside a LinearLayoutif you want) right below the ListView
  • Set the TextView's id as “emptyElement”
  • And inside the activity, set the setEmptyView()property to the ListView

1- Create an xml which will hold the ListViewand name it “my_activity” and an activity called “MyActivity”.

  1. Now, in the just created xml “my_activity”, you will have to set the ListView. And right below the ListView, you will have to add a TextView. This will be used to display the empty message.

Important: The TextView must have as id the following name: “emptyElement”. This name is mandatory. The message won't be displayed if you use another name.

This is how “my_activity” xml should look like:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"/>

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/emptyElement"
        android:text="The list is empty"
        android:textStyle="bold"
        android:textSize="15sp"
        android:visibility="gone"
        android:layout_centerInParent="true"
          android:textColor="@android:color/darker_gray"/>

</RelativeLayout>
  1. Create an xml for displaying items (when the list is not empty), and name it “list_item”.

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_item_text_view"
        android:textSize="20sp"
        android:padding="10dp"
        android:layout_marginLeft="5dp"/>
    

  2. Create a new Java class for the custom adapter which will be used by the ListView and name “MyCustomAdapter”. The code for the adapter is written below:

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    import java.util.ArrayList;
    
    
    public class MyCustomAdapter extends BaseAdapter {
    private ArrayList<String> mListItems;
    private LayoutInflater mLayoutInflater;
    
    public MyCustomAdapter(Context context, ArrayList<String> arrayList){
    
        mListItems = arrayList;
    
        //get the layout inflater
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    
    @Override
    public int getCount() {
        //getCount() represents how many items are in the list
        return mListItems.size();
    }
    
    @Override
    //get the data of an item from a specific position
    //i represents the position of the item in the list
    public Object getItem(int i) {
        return null;
    }
    
    @Override
    //get the position id of the item from the list
    public long getItemId(int i) {
        return 0;
    }
    
    @Override
    
    public View getView(int position, View view, ViewGroup viewGroup) {
    
        // create a ViewHolder reference
        ViewHolder holder;
    
        //check to see if the reused view is null or not, if is not null then reuse it
        if (view == null) {
            holder = new ViewHolder();
    
            view = mLayoutInflater.inflate(R.layout.list_item, null);
            holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
    
            // the setTag is used to store the data within this view
            view.setTag(holder);
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)view.getTag();
        }
    
        //get the string item from the position "position" from array list to put it on the TextView
        String stringItem = mListItems.get(position);
        if (stringItem != null) {
            if (holder.itemName != null) {
                //set the item name on the TextView
                holder.itemName.setText(stringItem);
            }
        }
    
        //this method must return the view corresponding to the data at the specified position.
        return view;
    
    }
    
    /**
     * Static class used to avoid the calling of "findViewById" every time the getView() method is called,
     * because this can impact to your application performance when your  list is too big. The class is static so it
     * cache all the things inside once it's created.
     */
    private static class ViewHolder {
    
        protected TextView itemName;
    
    }
    }
    
  3. Now go to MyActivityclass and add the code below:

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView; 
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class MyActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);
    
        ListView listView = (ListView) findViewById(R.id.listView);
    
        // Create an empty array list of strings
        List<String> items = new ArrayList<String>();
    
        // Set the adapter
        MyCustomAdapter adapter = new MyCustomAdapter(items);
        listView.setAdapter(adapter);
    
        // Set the emptyView to the ListView
        listView.setEmptyView(findViewById(R.id.emptyElement));
     }
     }
    

当你想在ListView为空时向用户显示消息时,你必须记住以下 3 个步骤:

  • 在其中的XMLListView声明,创建一个TextView(TextView的内心也可以是LinearLayout,如果你想)正下方 ListView
  • TextView的 id设置为“emptyElement”
  • 在活动中,将setEmptyView()属性设置为 ListView

1- 创建一个 xml,将保存ListView并命名为“my_activity”和一个名为“MyActivity”的活动。

  1. 现在,在刚刚创建的 xml“my_activity”中,您必须设置ListView. 在 正下方ListView,您必须添加一个TextView. 这将用于显示空消息。

重要提示:TextView 必须具有以下名称作为 id:“emptyElement”。此名称是必需的。如果您使用其他名称,则不会显示该消息。

“my_activity” xml 应该是这样的:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"/>

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/emptyElement"
        android:text="The list is empty"
        android:textStyle="bold"
        android:textSize="15sp"
        android:visibility="gone"
        android:layout_centerInParent="true"
          android:textColor="@android:color/darker_gray"/>

</RelativeLayout>
  1. 创建一个用于显示项目的xml(当列表不为空时),并将其命名为“list_item”。

    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_item_text_view"
        android:textSize="20sp"
        android:padding="10dp"
        android:layout_marginLeft="5dp"/>
    

  2. 为 ListView 将使用的自定义适配器创建一个新的 Java 类,并将其命名为“MyCustomAdapter”。适配器的代码如下:

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    import java.util.ArrayList;
    
    
    public class MyCustomAdapter extends BaseAdapter {
    private ArrayList<String> mListItems;
    private LayoutInflater mLayoutInflater;
    
    public MyCustomAdapter(Context context, ArrayList<String> arrayList){
    
        mListItems = arrayList;
    
        //get the layout inflater
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    
    @Override
    public int getCount() {
        //getCount() represents how many items are in the list
        return mListItems.size();
    }
    
    @Override
    //get the data of an item from a specific position
    //i represents the position of the item in the list
    public Object getItem(int i) {
        return null;
    }
    
    @Override
    //get the position id of the item from the list
    public long getItemId(int i) {
        return 0;
    }
    
    @Override
    
    public View getView(int position, View view, ViewGroup viewGroup) {
    
        // create a ViewHolder reference
        ViewHolder holder;
    
        //check to see if the reused view is null or not, if is not null then reuse it
        if (view == null) {
            holder = new ViewHolder();
    
            view = mLayoutInflater.inflate(R.layout.list_item, null);
            holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
    
            // the setTag is used to store the data within this view
            view.setTag(holder);
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)view.getTag();
        }
    
        //get the string item from the position "position" from array list to put it on the TextView
        String stringItem = mListItems.get(position);
        if (stringItem != null) {
            if (holder.itemName != null) {
                //set the item name on the TextView
                holder.itemName.setText(stringItem);
            }
        }
    
        //this method must return the view corresponding to the data at the specified position.
        return view;
    
    }
    
    /**
     * Static class used to avoid the calling of "findViewById" every time the getView() method is called,
     * because this can impact to your application performance when your  list is too big. The class is static so it
     * cache all the things inside once it's created.
     */
    private static class ViewHolder {
    
        protected TextView itemName;
    
    }
    }
    
  3. 现在转到MyActivity类并添加以下代码:

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.ListView; 
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class MyActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);
    
        ListView listView = (ListView) findViewById(R.id.listView);
    
        // Create an empty array list of strings
        List<String> items = new ArrayList<String>();
    
        // Set the adapter
        MyCustomAdapter adapter = new MyCustomAdapter(items);
        listView.setAdapter(adapter);
    
        // Set the emptyView to the ListView
        listView.setEmptyView(findViewById(R.id.emptyElement));
     }
     }
    

回答by srinivas

 TextView tv=(TextView) view.findViewById(R.id.empty);
 tv.setVisibiliy(View.GONE);