(Android) 如何使列表视图项目中的文本保持在一行中?

(Android) How can I make the text in my listview item to stay on one row?

我关于 SO 的第一个问题,如果我说错了,请告诉我。就像标题所说的那样,我希望我的列表视图的每个项目中的文本都保持在一行中(如果它们的长度超过适合的长度,则使它们以“...”或类似的东西结尾)。我的 android 应用程序中有一种 "recent searches" 将它们全部留在字符串数组中,然后我将它们显示在列表视图中,如下所示:

    ListView recenlist = (ListView) findViewById(R.id.recentChatList);

       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, recCharArray);
       recenlist.setAdapter(adapter);
       recenlist.setTextFilterEnabled(true);

其中 recCharArray 包含一堆大小不一的字符串,并显示在列表视图中。然而,他们应该留在一排,但没有。我试过 singleLine、maxLines,但无法正常工作。有什么想法吗?

然后在 XML:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recentChatList"
    android:layout_below="@+id/searchField"
    android:layout_alignParentStart="true"
    android:layout_marginTop="45dp" />

我四处搜索了很多,但似乎找不到适合我的解决方案,我需要一种新的方法吗?我需要彻底改变什么吗?

提前致谢!

请注意,您正在为 ListView 中的行使用预定义的 xml 文件 android.R.layout.simple_list_item_1。您可以在此处查看此文件中的代码: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/layout/simple_list_item_1.xml

尝试在布局文件夹中使用单个 TextView 制作您自己的布局文件 (custom_simple_list_item.xml) 并设置 android:singleLine = "true"android:ellipsize = "end"。重用前面link中的代码,类似这样:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:singleLine = "true"
    android:ellipsize = "end"
  />

然后,在适配器初始化中使用此文件:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.custom_simple_list_item, recCharArray);

您可以使用自定义 Adapter,您的 Adapter 将包含一个 TextView 并且 TextView 应该在一行中 (singleLine="true")。 linkListView 制作自定义适配器。