Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get view of preference with custom layout

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" />
like image 803
Ran Avatar asked Jun 21 '13 10:06

Ran


1 Answers

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

like image 137
Kof Avatar answered Oct 10 '22 19:10

Kof