Consider this example:
There is a minimal activity in android which inflates this layout as root:
<!-- FILE activity_preference.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/settings_container"/>
</LinearLayout>
In the activity's onCreate:
setContentView(R.layout.activity_preference);
Then I want to replace settings_container with my PreferenceFragmentCompat. I'm using the current androidx Jetpack library, this goes into the app's gradle file:
implementation 'androidx.preference:preference:1.1.0'
I've also created a custom PreferenceFragmentCompat for my needs, but it does not really do too much now:
public class MyPreferenceFragmentCompat extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
// get the screen
PreferenceScreen preferenceScreen = getPreferenceManager().createPreferenceScreen(getContext());
// add item(s)
CheckBoxPreference item_Confirmation;
item_Confirmation = new CheckBoxPreference(this);
item_Confirmation.setKey("config_Confirmation");
item_Confirmation.setTitle("Confirmation");
item_Confirmation.setSummary("Confirmation");
item_Confirmation.setDefaultValue(false);
preferenceScreen.addPreference(item_Confirmation);
// set this screen as default
setPreferenceScreen(preferenceScreen);
}
Here is how activity transacts my fragment:
getSupportFragmentManager().beginTransaction().replace(R.id.settings_container, new MyPreferenceFragmentCompat()).commit();
If you are using AndroidX, you can use Preference.setIconSpaceReserved(boolean iconSpaceReserved)
method.
So, you will have:
item_Confirmation.setIconSpaceReserved(false);
You can also check this answer.