[Android] Access widget layout of a custom preference

I wanted to use the widget layout of a custom card picker settings preference to show the selected cards, but it was quite difficult to do so.

First, the layout file has to be created. My file just contains an image view, which I want to update according to the chosen settings. It has to be added to the preference in the preference screen xml file like this:

android:widgetLayout="@layout/the_layout"

But the problem is: How to access this layout? A lot of solutions I found suggested to make a custom preference layout and override the onCreateView() method of the preference to apply it. But had some ugly consequences: The text style was different to the default preferences, so it would look bad in combination with other preferences.

The more elegant solution is to override the onCreateView() method, but not apply a new layout. This method returns the default layout, where the widget layout is located in. So I only had to use this layout to search my imageView in the following way:

@Override
protected View onCreateView(ViewGroup parent) {
    View view = super.onCreateView(parent);

    imageView = (ImageView) view.findViewById(R.id.your_image_id_here);
    
    //do something with it here

    return view;
}

If you don’t have a custom class for the preference yet, create it and override onCreateView() there.