Bhargav
Bhargav

Reputation: 227

Preference Not Displayed - Preference Fragment

I am trying to create a SettingsActivity and am using a Fragment extending PreferenceFragment to achieve this. My Activity is being displayed while the preference is not .

SettingsActivity.java

public class SettingsActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();

}

SettingsFragment.java

public  class SettingsFragment extends PreferenceFragment {



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref);
    Toast ts = Toast.makeText(getActivity(),"Working",Toast.LENGTH_SHORT);
    ts.show();
}

}

pref.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen  xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
    android:key="@string/prefsync"
    android:title="@string/pre_name"
    android:summary="@string/summary"
    android:defaultValue="true" />

 </PreferenceScreen>

enter image description here

Upvotes: 2

Views: 2036

Answers (1)

Jerry Saravia
Jerry Saravia

Reputation: 3837

I had the same issue while testing on a 1st Moto X phone. This is what I ended up doing and it works fine now: I added an empty layout to the SettingsActivity before adding the fragment.

public class SettingsActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState ){
        super.onCreate(savedInstanceState);

        //Need to set layout to blank if we want to add fragments to it.
        setContentView(R.layout.activity_settings);

        getFragmentManager()
                .beginTransaction()
                .add( android.R.id.content, new SettingsFragment() )
                .commit();
    }

}

The xml file that is loaded for the layout is the blank layout that Android Studio normally creates. It looks like this.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.wordscroll.wordscroll.SettingsActivity">

</RelativeLayout>

Upvotes: 4

Related Questions