Get view of preference with custom layout

依然范特西╮ 提交于 2020-01-01 04:30:07

问题


I have a preference android:layout gft. I've set the layout in the android:layout property of the preference in the xml file.

Now I need to do an initialization of a button in the layout (it's a +1 button). I need to get that button in the onCreate method (it's a +1 button) but when I use findViewById(button_id) , it returns null.

Is there some way to get the view of this preference?

UPDATE: It seems like the preference isn't created after I add the preference xml, so I get null. Where I can call findViewById so the button is already created?

Thanks.

Preferences xml:

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

</PreferenceScreen>

Preference layout 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" />

回答1:


You need to create a class that extends Preference, then override onBindView and you'll have access to the view.

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
    }

}

You'll probably have to override some more methods, read about custom preference in PreferenceActivity - http://developer.android.com/guide/topics/ui/settings.html



来源:https://stackoverflow.com/questions/17233440/get-view-of-preference-with-custom-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!