SwitchPreferenceCompat摘要文本被截断(过长)如何解决?
解决SwitchPreferenceCompat长摘要文本被截断的问题
方法一:自定义Preference布局(推荐)
默认的SwitchPreferenceCompat布局对摘要文本的TextView设置了固定最大行数,导致长文本被截断。我们可以通过自定义布局解除这个限制:
- 在
res/layout目录下创建新布局文件preference_switch_long_summary.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?android:attr/listPreferredItemHeight" android:gravity="center_vertical" android:paddingStart="16dp" android:paddingEnd="16dp" android:orientation="horizontal"> <RelativeLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:paddingTop="16dp" android:paddingBottom="16dp"> <TextView android:id="@android:id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceListItem" android:singleLine="true" android:ellipsize="marquee" android:fadingEdge="horizontal"/> <TextView android:id="@android:id/summary" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@android:id/title" android:textAppearance="?android:attr/textAppearanceListItemSecondary" android:maxLines="0" <!-- 关键:设为0表示不限制行数 --> android:ellipsize="none"/> <!-- 可选:不需要省略号则设为none --> </RelativeLayout> <androidx.appcompat.widget.SwitchCompat android:id="@android:id/switch_widget" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:focusable="false" android:clickable="false"/> </LinearLayout>
- 在你的
SwitchPreferenceCompat标签中指定该自定义布局:
<SwitchPreferenceCompat app:key="@string/key" app:persistent="false" app:summary="@string/very_long_text" app:title="@string/title" app:layout="@layout/preference_switch_long_summary" /> <!-- 添加这一行 -->
方法二:通过代码动态修改
如果不想自定义布局,可在Preference加载完成后动态修改摘要TextView的属性:
Kotlin版本(在PreferenceFragmentCompat的onViewCreated中):
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val preference = findPreference<SwitchPreferenceCompat>(getString(R.string.key)) preference?.view?.findViewById<TextView>(android.R.id.summary)?.apply { maxLines = 0 ellipsize = null } }
Java版本:
@Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); SwitchPreferenceCompat preference = findPreference(getString(R.string.key)); if (preference != null) { TextView summaryView = preference.getView().findViewById(android.R.id.summary); if (summaryView != null) { summaryView.setMaxLines(0); summaryView.setEllipsize(null); } } }
注意事项
android:maxLines="0"表示TextView会根据内容自动调整高度,展示全部文本。- 若需要文本末尾显示省略号但允许换行,可将
android:ellipsize设为end,同时maxLines设为你需要的行数(比如20)而非0。
内容的提问来源于stack exchange,提问作者Targetbus12
相关产品推荐
相关产品推荐

