Reputation:
I'm having problem with ActionBar and app-compat-v21.
ActionBar is shown everywhere except PreferenceActivity
I tried to follow recommendations and made it with Fragments:
public class PrefsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
and
public class PrefsActivity extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PrefsFragment()).commit();
}
}
However, there's no ActionBar.
BTW, in Styles.xml
is set <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
What's wrong?
Upvotes: 1
Views: 1273
Reputation: 363745
In order to use the new appcompat v21 you have to:
AppCompatActivity
The PreferenceActivity
doesn't extend the AppCompatActivity
.
It is the reason why there is no actionbar in your code.
As solution you can create a PreferenceFragment as you are doing and use it in a standard AppCompatActivity.
UPDATED 12/06/2015
With the new 22.1+ appcompat you can use also the AppCompatDelegate to extend AppCompat's support to any Activity.
You can check this official link to AppCompatPreferenceActivity, where you can find an example of this technique.
Upvotes: 4
Reputation: 1040
With the app compat the toolbar needs to be defined in the layout. You can create a layout for the Settings Activity with the toolbar and then add the preference fragment.
For example:
activity_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
layout="@layout/toolbar" />
<fragment
android:id="@+id/settings_fragment"
android:name="com.bla.bla.MyPreferenceFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toolbar" />
</RelativeLayout>
SettingsActivity:
public class SettingsActivity extends ActionBarActivity{
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar actionbar = (Toolbar) findViewById(R.id.toolbar);
actionbar.setTitle("Settings");
actionbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SettingsActivity.this.finish();
}
});
}
MyPreferenceFragment:
public static class MyPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);;
}
}
edit: Updated the answer to use ActionBarActivity instead of the deprecated PreferenceActivity
Upvotes: 1