#StackBounty: #android #android-preferences Android: How to know when Preference fragment is opened

Bounty: 50

I got a SettingsActivity extending AppCompatPreferenceActivity.

I load headers like this:

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.pref_headers, target);
}

pref_headers.xml:

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- These settings headers are only used on tablets. -->

    <header
        android:fragment="com.lifo.skipandgo.activities.SettingsActivity$GeneralPreferenceFragment"
        android:icon="@drawable/ic_info_black_24dp"
        android:title="@string/pref_header_general"/>

    <header
        android:fragment="com.lifo.skipandgo.activities.SettingsActivity$NotificationPreferenceFragment"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/pref_header_notifications" />

    <header
        android:fragment="com.lifo.skipandgo.activities.SettingsActivity$DataSyncPreferenceFragment"
        android:icon="@drawable/ic_sync_black_24dp"
        android:title="@string/pref_header_data_sync" />

</preference-headers>

Now I added an Actionbar like explained here: https://gldraphael.com/blog/adding-a-toolbar-to-preference-activity/

private void setupActionBar() {
        getLayoutInflater().inflate(R.layout.pref_toolbar, (ViewGroup)findViewById(android.R.id.content));
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (toolbar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        int verticalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int) getResources().getDimension(R.dimen.activity_vertical_margin) + 30, getResources().getDisplayMetrics());
        getListView().setPadding(horizontalMargin, topMargin, horizontalMargin, verticalMargin);
    }

This works fine. But when I click on one of the headers in the Activity a PreferenceFragment is loaded. In this moment the content is below the actionbar. I would need to again call the getListView().setPadding(). But how can I do this? How can I know when the fragment is opening?


Get this bounty!!!

Leave a Reply