向PreferenceFragment添加自定义布局

Cos*_*nci 7 android

我有一个偏好屏幕层次结构的首选项片段.我想添加一个自定义布局来定义"关于作者"部分,将imageview添加到元素和链接(意图浏览器).我搜索了但是没有找到关于这个主题的任何资源.

Car*_*men 16

在您的首选项xml文件(res/xml/prefs.xml)中,添加Preference一个自定义布局:

<Preference
    android:layout="@layout/custom_preference"/>
Run Code Online (Sandbox Code Playgroud)

layout/custom_preference.xml带有a ImageViewTextView带有将在浏览器中打开的链接的示例:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_book" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://www.mylink.com"
        android:autoLink="all"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这是屏幕截图中的最后一个偏好: 自定义首选项的首选项屏幕

  • 我成功地将自定义布局添加到我的preferencefragment,但是如何在首选项片段类中引用该视图?我需要与该视图进行交互以将点击侦听器附加到我在自定义布局中添加的按钮. (8认同)
  • 是否可以在运行时检查自定义布局文本? (2认同)
  • 如何动态处理自定义内容? (2认同)
  • 我想我们永远不会知道。 (2认同)

Mr-*_*IDE 6

这只是 Carmen 回答(2016 年 10 月 30 日)的后续:

如果您想动态更改自定义布局上的属性,则在屏幕加载后,您不能使用如下内容:

PreferenceScreen customPref = (PreferenceScreen) findPreference("customPreference");
View prefRow = customPref.getView(null, null);
ImageView imageView = (ImageView)prefRow.findViewById(R.id.image_view);
imageView.setImageResource(R.drawable.whatever);
Run Code Online (Sandbox Code Playgroud)

虽然它不会崩溃,但它实际上不会做任何事情。这很奇怪而且令人困惑。

您必须使用扩展android.preference.Preference和重写的自定义类onBindView()来更改自定义布局上的属性。这里解释了该技术:如何管理自定义首选项布局 [注意:对于 PreferenceFragmentCompat,您必须扩展androidx.preference.Preference和覆盖onBindViewHolder()]

另一种方法是使用getView()但确保使用View view = super.getView(convertView, parent);Android Set Custom Preference Layout