findViewById null on PreferenceFragment

34
July 11, 2019, at 8:20 PM

I am using a custom layout in my settings fragment, like below:

<Preference
    android:key="customiseNavBtnPreview"
    android:layout="@layout/custom_layout" />

This displays on my settings page just fine but I want to be able to manipulate like I would in a normal activity (e.g. add click events to buttons, change backgrounds on the fly etc).

Normally I would just call findByViewId(R.id.some_child_of_custom_layout) to pick up Views in the layout but it doesn't seem to work and I get null reference errors as if the view doesn't exist. If I hack in a short delay, it sorta picks it up, but I don't want a delay.

Here is my activity creation code:

public class BrowserSettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = new Preferences(this);
        prefsFragment = new PrefsFragment();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getFragmentManager().beginTransaction().replace(
            android.R.id.content,
            prefsFragment
        ).commit();
    }

Here is the fragment:

public static class PrefsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((BrowserSettingsActivity) getActivity()).prefsFragment = this; // Required for when activity.recreate() is called when applying theme
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.pref_general);
        BrowserSettingsActivity activity = (BrowserSettingsActivity) getActivity();
        ImageButton test = activity.findViewById(R.id.navButton1Preview);
        // test is null...

I'd really appreciate an explanation of WHY this doesn't work as well. I don't really understand how I should be using fragments either.. Do I keep my view references in there or on the activity class? If I can't get a grasp on this I'm going to have to redo my whole settings page as a normal Activity as everything about this seems counter-intuitive to me. Thanks!!!

READ ALSO
The right way to find SD-Card path and in work with its files

The right way to find SD-Card path and in work with its files

I am creating a file manager for android and the last thing I have to do is access to sd-card files

42
How to make two toolbars? [on hold]

How to make two toolbars? [on hold]

I am trying to make this kind of activity:

35
Is there a way to put a video into an AlertDialog? [duplicate]

Is there a way to put a video into an AlertDialog? [duplicate]

This question already has an answer here:

33
Android : How to integrate Push Notification to an already existing app?

Android : How to integrate Push Notification to an already existing app?

How to integrate Push Notification to an already existing android app?

42