onResume() method and ListPreferences Android - java

PreferenceActivity:
public class UsersettingsActivity extends PreferenceActivity
{
public EditTextPreference nomePreferences;
public static float currValue;
public static ListPreference lista;
public static CharSequence currText;
public static String ilmionome;
public CheckBoxPreference checkboxPrefSpeech;
public CheckBoxPreference checkboxPref;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.overridePendingTransition(R.anim.in, R.anim.out);
/** Customizzo la actionbar */
ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.layout.actionbarcustom);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
nomePreferences = (EditTextPreference)getPreferenceManager().findPreference("nomepreferenze");
lista = (ListPreference)getPreferenceManager().findPreference("prefSyncFrequency");
currText = lista.getEntry();
currValue = Float.parseFloat(lista.getValue());
Toast valori = Toast.makeText(getBaseContext(), currText, Toast.LENGTH_SHORT);
valori.show();
if(currValue == 2){
currValue = MainActivity.tts.setSpeechRate(2.0f);
} else if (currValue == 1) {
currValue = MainActivity.tts.setSpeechRate(1.0f);
} else if (currValue == 0.5) {
currValue = MainActivity.tts.setSpeechRate(0.5f);
}
}
}
the arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="syncFrequency">
<item name="2">Double/item>
<item name="1">Normal</item>
<item name="0">half</item>
</string-array>
<string-array name="syncFrequencyValues">
<item name="2">2</item>
<item name="1">1</item>
<item name="0">0.5</item>
</string-array>
</resources>
Well, if i choose "Double" for example, and i exit from this activity to come back to my MainActivity, the speech rate still the same! I need exit from app and then it works! So it means that in the onResume() of MainActivity needs something that calls the values from the PreferenceActivity.. Understand now?
EDIT:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:summary="Opzioni lettura sms"
android:fontFamily="sans-serif-light"
android:title="Opzioni">
<CheckBoxPreference
android:key="firstDependent"
android:fontFamily="sans-serif-light"
android:summary="#string/autorizza"
android:title="#string/letturanotifiche"
/>
<EditTextPreference
android:title="#string/nomepreferences"
android:key="nomepreferenze"
android:fontFamily="sans-serif-light"
android:summary="#string/nomepreferencesdesc"
android:inputType="text"
android:dialogTitle="#string/nameis"
/>
<ListPreference
android:key="prefSyncFrequency"
android:entries="#array/syncFrequency"
android:summary="#string/pref_sync_frequency_summary"
android:entryValues="#array/syncFrequencyValues"
android:title="#string/pref_sync_frequency" />
</PreferenceCategory>
<!--Any other categories include here-->
</PreferenceScreen>

public class SomePreference extends PreferenceActivity implements OnSharedPreferenceChangeListener{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.task_pref);
SharedPreferences SP = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// Register OnChangeListener
SP.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
//Make sure the item changed was the list_preference
if(key.equals("")){
String value = sharedPreferences.getString(key, "Double");
Intent i = new Intent(this, Main.class);
startActivity(i);
}
}
}
Main Activity
public class Main extends Activity{
protected void onCreate(Bundle savedInstanceState){
\\setup rest here.
SharedPreferences share_someting = PreferenceManager.getDefaultSharedPreferences(this);
String ss = share_something.getString("prefSyncFrequency", "Double");
}
protected void onResume(){
\\setup rest here.
SharedPreference share_something = PreferenceManager.getDefaultSharedPrefernce(this);
String ss = share_something("prefSyncFrequency", "Double");
}

protected void onCreate(){
text_speech();
}
protected void onResume(){
text_speech();
}
public void text_speech(){
SharedPrefernces spp = PreferenceManager.getDefaultSharedPreferences(this);
String sf = spp.getString("prefSyncFrequency", "Double");
if(sf.equals("two")){
currValue = MainActivity.tts.setSpeechRate(2.0f);
}else if(sf.equals("single")){
currValue = MainActivity.tts.setSpeechRate(1.0f);
}else (sf.equals("half")){
currValue = MainActivity.tts.setSpeechRate(0.5f);
}
I just changed below to follwing, I think its easier work this way.
<string-array name="syncFrequencyValues">
<item >two</item>
<item >single</item>
<item >half</item>
</string-array>

Related

android tabs allCaps works only for first tab

I'm trying to set my tabs text textAllCaps to false.
For some reason only firs tab has needed results, but the second is still all caps.
https://imgur.com/a/fnv2DzY
I've set tabTextAppearance to MyCustomTextAppearance and in styles two attributes are set to textAllCaps, android:textAllCaps are set to false
activity:
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/appbar"
app:tabTextAppearance="#style/MyCustomTextAppearance" />
in styles:
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabTextAppearance">#style/MyCustomTextAppearance</item>
</style>
<style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab">
<item name="textAllCaps">false</item>
<item name="android:textAllCaps">false</item>
</style>
in Java:
public class NewLoginActivity extends BaseActivity implements
RegisterFragment.OnFragmentInteractionListener,
LoginFragment.OnFragmentInteractionListener {
public ActivityNewLoginBinding binding;
private List<String> titles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_new_login);
setSupportActionBar(binding.toolbar);
setToolBarTitle(getSupportActionBar(), getResources().getString(R.string.login_action_title));
if (getSupportActionBar() != null){
getSupportActionBar().setHomeButtonEnabled(false); // Disable the button
getSupportActionBar().setDisplayHomeAsUpEnabled(false); // Remove the left caret
getSupportActionBar().setDisplayShowHomeEnabled(false); // Remove the icon
}
binding.tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
binding.tabLayout.setTabMode(TabLayout.MODE_FIXED);
titles = new ArrayList<>();
titles.add(getString(R.string.login_action_title));
titles.add(getString(R.string.regi));
Bundle bundle = getIntent().getExtras();
LoginTabAdapter tabAdapter;
tabAdapter = new LoginTabAdapter(getSupportFragmentManager(), this, titles);
binding.viewPager.setAdapter(tabAdapter);
binding.viewPager.setOffscreenPageLimit(1);
binding.tabLayout.setupWithViewPager(binding.viewPager);
if (bundle != null && bundle.containsKey("signup")) {
binding.viewPager.setCurrentItem(2);
}
}

Passing ArrayList from Fragment A to Fragment B when user clicked navbar (of Fragment B)

I am new to Android & Fragment please help me. My app is using navbar menu which consists of Home (HomeFragment) and History (HistoryFragment).
I want to pass ArrayList (existingRecords) and a Record object (todayRecord) from HomeFragment to HistoryFragment when user navigate from Home to navbar and click on History. I've configured to send existingRecords to MainActivity class as below. I don't know how to pass todayRecord into the intent.
HomeFragment.class:
#Override
public void onStop() {
super.onStop();
//compare if the date of last record is the same as today
//if same, update today's record
Log.d(msg, "The onStop() event");
if(recordExist){
updateLastRecord(todayRecord);
Log.d(msg, "existing record updated");
}
//if record not found, add new record
else {
addRecord(todayRecord);
Log.d(msg, "New record added");
}
sendDataToMainActivity();
}
public void sendDataToMainActivity(){
Log.d("Android: ", "HomeFragment: Sending Data to MainActivity");
Intent intent = new Intent(getActivity().getBaseContext(), MainActivity.class);
intent.putParcelableArrayListExtra("existingRecords", existingRecords);
getActivity().startActivity(intent);
}
I don't know how to call sendReceiveData() when user clicked on History (R.id.nav_history) on navbar menu.
MainActivity.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_history, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
loadAdmob();
}
public void sendReceiveData(){
//receive data from HomeFragment
Intent intent = getIntent();
existingRecords = intent.getParcelableArrayListExtra("existingRecords");
//send data to History fragment
Bundle bundle=new Bundle();
bundle.putParcelableArrayList("existingRecords", existingRecords);
//set Fragmentclass Arguments
HistoryFragment fragobj=new HistoryFragment();
fragobj.setArguments(bundle);
}
I've configured HistoryFragment.class to receive data but when I ran the code, bundle is null because I have no way to pass the bundle in MainActivity.
HistoryFragment.class:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
historyViewModel = ViewModelProviders.of(this).get(HistoryViewModel.class);
View root = inflater.inflate(R.layout.fragment_history, container, false);
Bundle bundle = this.getArguments();
if(bundle!=null){
// handle your code here.
existingRecords = savedInstanceState.getParcelableArrayList("existingRecords");
txtThisMonthSummary = root.findViewById(R.id.txtThisMonthSummary);
txtThisWeekSummary = root.findViewById(R.id.txtThisWeekSummary);
txtThisMonthSummary = root.findViewById(R.id.txtYearSummary);
Log.d("Android: ", "HistoryFragment: Data received");
summary = new History(existingRecords);
txtThisWeekSummary.setText(summary.getWeeklySum());
txtThisMonthSummary.setText(summary.getMonthlySum());
txtThisYearSummary.setText(summary.getYearlySum());
}
return root;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_zikir"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_history"
android:icon="#drawable/ic_achievement"
android:title="#string/menu_history" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_achievement" />
</group>
</menu>
Based on #kelvin feedback, I have managed to retrieve the data from SharedPreferences in HomeFragment. I didn't occur to me that data stored in SharedPreferences can be accessed through any class. *Noob*
Share Preference name/key:
public static final String PREFS_NAME = "Daily Zikir";
public static final String RECORDLIST = "Records";
Code used to store data, called in HomeFragment:
public void saveRecords(List records){
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
builder.excludeFieldsWithoutExposeAnnotation();
Gson sExposeGson = builder.create();
String jsonRecords = sExposeGson.toJson(records);
editor.putString(RECORDLIST, jsonRecords);
editor.commit();
Log.d("Android: ", "Jason string saved: "+ jsonRecords);
}
Code used to retrieve data, called in HistoryFragment:
public ArrayList loadRecords() {
// used for retrieving arraylist from json formatted string
SharedPreferences settings;
List records;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains(RECORDLIST)) {
String jsonFavorites = settings.getString(RECORDLIST, null);
GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
builder.excludeFieldsWithoutExposeAnnotation();
Gson sExposeGson = builder.create();
Record[] recordItems = sExposeGson.fromJson(jsonFavorites, Record[].class);
records = Arrays.asList(recordItems);
records = new ArrayList(records);
} else
return null;
return (ArrayList) records;
}
Will explore usage of SQLlite & ViewModel moving forward but this will do for now.

Complete code for adding an OnClickListener to a Preference

Ok I swear this is the last time I will ask this question. I've tried a trillion different solutions and non of them work.
First here is the blank Settings activity as created by Android Studio:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
}
And here is my preferences xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:id="#+id/resetSettings"
android:defaultValue="true"
android:key="reset_settings"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="#string/reset_description"
android:title="#string/reset_title" />
<SwitchPreference
android:defaultValue="false"
android:key="switch_preference"
android:summary="Instead of values from 0 to 255, the seekBar will use percentages"
android:title="Use Percentages" />
</PreferenceScreen>
I want an OnClickListener attached to the Reset preference so it can open an Alert Dialog that asks the user if they want to delete all app data.
In settings fragment in onCreatePreference add:
Preference
resetPreference=findPreference("your Preference key");
Then for the click listener add:
resetPreference.setOnPreferenceClickListenere(new
Preference.OnPreferenceClickListener() {
#overide
public boolean onPreferenceClick(Preference preference)
{
//your code goes here
return false;
}
});

Toolbar is not shown in activities when extending Base Activity that implements ToolBar

I am a beginner Android developer and I have been struggling the issue that I can't see the toolbar in any activity that inherits Base Activity. According to other resource, to use the same toolbar in the different activities. I have to implement it in Base Activity and inherit it where I need to use it. Could anyone help me figure out the problem?
styles.xml
<resources>
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<style name="AppTheme" parent="AppBaseTheme">
</style>
</resources>
quiz.menu.xml inside of menu folder
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/contact"
android:icon="#drawable/ic_contacts_black_24dp"
android:title="Contact"
app:showAsAction="ifRoom" />
<item android:id="#+id/language"
android:title="Language"
app:showAsAction="never" />
<item android:id="#+id/speech"
android:title="Speech"
app:showAsAction="never">
<munu>
<item android:id="#+id/subitem1"
android:title="Sub Item 1"/>
<item android:id="#+id/subitem2"
android:title="Sub Item 2"/>
</munu>
</item>
</menu>
BaseActivity
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.quiz_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.contact:
Toast.makeText(this, "Contact is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.language:
Toast.makeText(this, "Language is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.speech:
Toast.makeText(this, "Speech is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.subitem1:
Toast.makeText(this, "Language is selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.subitem2:
Toast.makeText(this, "Speech is selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
WelcomeActivity (inherits base Activity)
public class WelcomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
final Button databaseButton = findViewById(R.id.database);
databaseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
Intent databaseIntent = new Intent(WelcomeActivity.this, Questionnaire.class);
startActivity(databaseIntent);
}
});
}
Questionnaire
public class Questionnaire extends BaseActivity {
public Spinner languageSpinner;
public int languageId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questionnaire);
...
}
}
The answer is actually simple. You firstly set contentview in OnCreate() method of the BaseActivity class, then you change the view to another xml file in OnCreate() methods of the child classes.
What I suggest is that you do not implement OnCreate() method in BaseActivity class but implement SetContentView() method in BaseActivity.
In short, delete onCreate() method from BaseActivity() and add setContentView() method in the below.
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
P.S - Your quiz_menu.xml file does not look like a menu file. :)
P.P.S - Let me know if it works, or if you have troubles. :)

How to create Settings with toolbar in android

I have a Settings Preference screen.It has a ListPreference and a CheckBoxPreference. I want to change my app's date format when I choose an item of ListPreference. Also, by the CheckBoxPreference I want to show/hide notification on the status bar. Can anyone tell what I have to do to achieve that.
Also, how can I add a toolbar to the preference screen? I am stuck here. Please help. Thanks in advance.
I am stuck here. Please help.
Thanks in advance.
MainActivity.java
public void setCurrentDateOnView() {
String dateFormat = "dd - MM - yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
tv_Current_Date.setText(simpleDateFormat.format(calendar_now.getTime()));
String short_weekday = new DateFormatSymbols().getShortWeekdays()[day_of_current_week];
tv_Current_weekday.setText(short_weekday);
til_Current_Date.setError(null);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent_settings = new Intent(this, SettingsActivity.class);
startActivity(intent_settings);
Toast.makeText(this, "You have clicked on settings action menu.", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
NotificationManager mNotifyManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean notifyEnabled = sharedPreferences.getBoolean("pref_cb_notification", true);
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notifyEnabled) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean isChecked = sharedPreferences.getBoolean("pref_cb_notification", false);
if (isChecked) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
//Method to show notification
public void showNotification() {
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(SettingsActivity.this)
.setSmallIcon(R.drawable.ic_notifications_white_24dp)
.setContentTitle("My Application")
.setSubText("Tap to start");
Intent resultIntent = new Intent(SettingsActivity.this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent
.getActivity(SettingsActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//System.currentTimeMillis();
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
//notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotifyManager.notify(1, notification);
}
//Method to hide notification
public void hideNotification() {
mNotifyManager.cancel(1);
}
}
Settings image
for adding toolbar you just need to use the coordinator layout in the layout file of your activity. Preference activity has simple layout like others and you just inflate preference fragments inside a container.
add appcompact design support library to your build.gradle
compile 'com.android.support:appcompat-v7:21.0.3'
Add toolbar.xml to your layout folder
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:elevation="4dp"
>
</android.support.v7.widget.Toolbar>
Then include toolbar in your activity.xml
<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"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<TextView
android:layout_below="#+id/tool_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/TextDimTop"
android:text="#string/hello_world" />
</RelativeLayout>
then you need to set up it in your activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
and then by using onCreateOptionsMenu you can add settings menu on it.

Categories