使用自定义布局查看首选项视图

Ran*_*Ran 10 android android-preferences

我有一个偏好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>
Run Code Online (Sandbox Code Playgroud)

首选项布局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" />
Run Code Online (Sandbox Code Playgroud)

Kof*_*Kof 12

您需要创建一个扩展的类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
    }

}
Run Code Online (Sandbox Code Playgroud)

您可能必须覆盖更多方法,请阅读PreferenceActivity中的自定义首选项 - http://developer.android.com/guide/topics/ui/settings.html