使用自定义布局获取首选项视图

12

我有一个偏好 android:layout gft。

我已经在xml文件中的偏好设置的android:layout属性中设置了布局。

现在我需要初始化布局中的一个按钮(它是一个+1按钮)。 我需要在onCreate方法中获取该按钮(它是一个+1按钮),但当我使用findViewById(button_id)时,它返回null。

是否有一些方法可以获取此偏好的视图?

更新:似乎在添加偏好xml后偏好设置没有被创建,所以我得到了null。在哪里可以调用findViewById,使按钮已经被创建?

谢谢。

偏好设置xml:

<Preference android:title="Rate this app"
    android:key="rate"
    android:widgetLayout="@layout/plusone_pref"/>

</PreferenceScreen>

偏好设置布局的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.plus.PlusOneButton xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="@+id/plus_one_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:focusable="false"
plus:size="standard" />

在preferences.xml被填充后,你可以添加自定义布局。 例如: ((listView.parent as FrameLayout).parent as LinearLayout).addView(customView,0)listView是来自androidx.preferences.R.id.recycler_view的recyclerView。 - msevgi
1个回答

15
你需要创建一个继承自Preference的类,然后重写onBindView方法,这样你就可以访问视图了。
public class MyPreference extends Preference {

    ...

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        View myView = (View) view.findViewById(R.id.my_id);
        // ... do stuff
    }

}

你可能需要覆盖一些额外的方法,阅读PreferenceActivity中的自定义偏好设置 - http://developer.android.com/guide/topics/ui/settings.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接