Here is my preference activity:
package com.example.hms.test;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefsActivity extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
here I want to show an actionbar with name settings and a back button to home
AppCompatActivity just use: Toolbar toolbar = findViewById(R. id. toolbar); setSupportActionBar(toolbar); getSupportActionBar().
This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
getActionBar(). setDisplayShowHomeEnabled(false); //disable back button getActionBar(). setHomeButtonEnabled(false); In a older android phone, the back button is removed with these two code lines.
The answer Pooya gave won't work for a PreferenceActivity. Instead make your class extend AppCompatActivity, and use a PreferenceFragment to load up the preference. Here is my code for settings:
public class MyPrefsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
public static class MyPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
Put the activity in your AndroidManifest.XML:
<activity android:name=".MyPrefsActivity"
android:label="Preferences"
android:theme="@style/AppTheme"/>
And now you can start the settings activity using an intent in my Main Activity (or whichever parent activity you have) as normal:
Intent prefsIntent = new Intent(activity, MyPrefsActivity.class);
activity.startActivity(prefsIntent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With