1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
package com.mapswithme.maps.settings;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceScreen;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseToolbarActivity;
public class SettingsActivity extends BaseToolbarActivity
implements PreferenceFragmentCompat.OnPreferenceStartFragmentCallback,
PreferenceFragmentCompat.OnPreferenceStartScreenCallback
{
@Nullable
private String mLastTitle;
@Override
protected int getContentLayoutResId()
{
return R.layout.activity_settings;
}
@Override
protected Class<? extends Fragment> getFragmentClass()
{
return SettingsPrefsFragment.class;
}
@Override
@SuppressWarnings("unchecked")
public boolean onPreferenceStartFragment(PreferenceFragmentCompat caller, Preference pref)
{
String title = TextUtils.isEmpty(pref.getTitle()) ? null : pref.getTitle().toString();
try
{
Class<? extends Fragment> fragment = (Class<? extends Fragment>) Class.forName(pref.getFragment());
replaceFragment(fragment, title, pref.getExtras());
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return true;
}
@Override
public boolean onPreferenceStartScreen(PreferenceFragmentCompat preferenceFragmentCompat, PreferenceScreen preferenceScreen)
{
Bundle args = new Bundle();
args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.getKey());
replaceFragment(SettingsPrefsFragment.class, preferenceScreen.getTitle().toString(), args);
return true;
}
public void replaceFragment(@NonNull Class<? extends Fragment> fragmentClass,
@Nullable String title, @Nullable Bundle args)
{
final int resId = getFragmentContentResId();
if (resId <= 0 || findViewById(resId) == null)
throw new IllegalStateException("Fragment can't be added, since getFragmentContentResId() " +
"isn't implemented or returns wrong resourceId.");
String name = fragmentClass.getName();
final Fragment fragment = Fragment.instantiate(this, name, args);
getSupportFragmentManager().beginTransaction()
.replace(resId, fragment, name)
.addToBackStack(null)
.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();
if (title != null)
{
Toolbar toolbar = getToolbar();
if (toolbar != null && toolbar.getTitle() != null)
{
mLastTitle = toolbar.getTitle().toString();
toolbar.setTitle(title);
}
}
}
@Override
public void onBackPressed()
{
if (mLastTitle != null)
getToolbar().setTitle(mLastTitle);
super.onBackPressed();
}
}
|