Use the action that extends AppCompatActivity, which contains your toolbar that references the layout file, as shown below.
public class UserSettingPreference extends AppCompatActivity { Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.toolbar); toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Settings"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); getFragmentManager().beginTransaction().replace(R.id.fragment_container, new UserPreferenceFragment()).commit(); } }
Define your layout containing the toolbar and framemute to hold the fragment
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Toolbar xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#80000000" android:minHeight="?android:attr/actionBarSize" app:contentInsetEnd="0dp" app:contentInsetLeft="0dp" app:contentInsetRight="0dp" app:contentInsetStart="0dp"/> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
Then define the fragment fragment fragment as shown below -
public class UserPreferenceFragment extends PreferenceFragment
To reference your preference.xml override the onCreate fragment as shown below -
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.fragment_preference); }
To reference individual elements within your .xml preference method, use the getPreferenceScreen method
switchPreference = (SwitchPreference) getPreferenceScreen().findPreference("floating_widget");
source share