EdittextPreference to set custom TextView - android

I have a TextView on my MainActivity which is a welcome text, it has a condition that if the user of my application has not set a username, it would only display "welcome" and if the user already sets their username, it would display the "welcome" text plus their username which has already assigned.
I am using the EdittextPreference & SharedPreference in this cause
the problem is, even the username has been set, it seems it is has not been set, because it doesn't trigger the if else condition i wrote between MainActivity & Settings, it still display the only "welcome" text.
I need some clue here..
my MainActivity.java >> https://paste.ubuntu.com/p/2n33ZzVkY4/
my Settings.java >> https://paste.ubuntu.com/p/JBWSqJfmG6/

you need to save there data in share preference and check if any data exist in share preference then display welcome + its user name both

You are saving the data on SharedPreferences.
You should use below code to get the data from sharedPreferences.
SharedPreferences sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPreference.getString("username", "");

Try the following complete example:
1) DemoActivity.class--------
public class DemoActivity extends AppCompatActivity{
private TextView tv;
private SharedPreferences demo_preferences;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity);
demo_preferences = getSharedPreferences("demo_preference",
0);
tv = (TextView) findViewById(R.id.tv);
if(demo_preferences != null) {
String usn = demo_preferences.getString("username", "");
if (usn.isEmpty()) {
tv.setText("Welcome");
} else {
tv.setText("Welcome " + usn);
}
}else{
tv.setText("Welcome");
}
}
#Override
protected void onResume() {
super.onResume();
if(demo_preferences != null) {
String usn = demo_preferences.getString("username", "");
if (usn.isEmpty()) {
tv.setText("Welcome");
} else {
tv.setText("Welcome " + usn);
}
}else{
tv.setText("Welcome");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.demo_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(DemoActivity.this , PrefDemoActivity.class);
startActivity(i);
break;
default:
throw new RuntimeException("unknown menu selection");
}
return true;
}
}
2) PrefDemoActivity:-------
public class PrefDemoActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
DemoEditPreferences mDemoPrefsFragment = new DemoEditPreferences();
mFragmentTransaction.replace(android.R.id.content, mDemoPrefsFragment);
mFragmentTransaction.commit();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
3) DemoEditPreferences:---------
public class DemoEditPreferences extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
private SharedPreferences demo_preferences;
private int preferencesToEdit;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demo_preferences = getActivity().getSharedPreferences("demo_preference",
0);
preferencesToEdit = R.xml.demo_preferences;
String preferenceName = getResources().getString(R.string.pref_sensor_key);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(preferenceName);
preferenceManager.setSharedPreferencesMode(0);
getActivity().setTitle("Demo Preferences");
addPreferencesFromResource(preferencesToEdit);
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(findPreference(key) != null) {
if(findPreference(key).getKey().equals("username")) {
if(sharedPreferences.getString("username","").equals("")){
setString("username","");
}else{
setString("username",sharedPreferences.getString("username","----"));
}
}
updatePrefSummary(findPreference(key));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
public void setString(String preferenceName, String value)
{
SharedPreferences.Editor editor = demo_preferences.edit();
editor.putString(preferenceName, value);
editor.apply();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setBackgroundColor(getResources().getColor(android.R.color.white));
return view;
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
4) demo_activity.xml:------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Welcome"
android:id="#+id/tv"
android:gravity="center"
android:background="#android:color/holo_blue_light"/>
5) demo_menu.xml---------------
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/menu_settings"
android:title="Settings"
android:titleCondensed="Settings"
android:orderInCategory="1">
</item>
</menu>
6) demo_preferences:---------
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Demo">
<EditTextPreference
android:key="username"
android:title="UserName"
android:defaultValue="----"
android:summary="----"
android:selectAllOnFocus="true"
android:singleLine="true">
</EditTextPreference>
</PreferenceCategory>
</PreferenceScreen>
7) Don't forget to add both activities to the manifest.

Related

How to save fragment state

I have SettingActivity. It contains SettingFragment (with ListPreference) and another AudioSamplingSeekBarFragment(with my custom preference in it). When i choose some item in ListPreference, i recreate my AudioSamplingSeekBarFragment with chosen data from ListPreference. like this:
public class SettingsFragment extends PreferenceFragment {
private static Logger log = Logger.getLogger(SettingsFragment.class.getName());
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference outputFormatPref = (ListPreference) findPreference(getResources().getString(R.string.key_encoder));
outputFormatPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
MySharedPreferences.setAudioEncoder(getActivity(), (String) newValue);
**embedSeekBarWithFormat((String) newValue);**
return true;
}
});
}
**public void embedSeekBarWithFormat(String format) {
try {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
AudioSamplingSeekBarFragment fragment = (AudioSamplingSeekBarFragment) manager.findFragmentByTag(AudioSamplingSeekBarFragment.TAG);
if (manager.findFragmentByTag(AudioSamplingSeekBarFragment.TAG) != null) {
transaction.remove(fragment);
}
AudioSamplingSeekBarFragment newFragment = new AudioSamplingSeekBarFragment();
Bundle bundle = new Bundle();
bundle.putInt(AudioSamplingSeekBarFragment.STATE_FORMAT, Integer.parseInt(format));
newFragment.setArguments(bundle);
transaction.add(R.id.seekBar_container, newFragment, AudioSamplingSeekBarFragment.TAG);
transaction.commit();
} catch (Exception e) {
log.log(Level.SEVERE, "Exception: ", e);
}
}
}**
So when i quite the SettingActivity and go into again my AudioSamplingSeekBarFragment doesn't save state.
I put my fragment in onSaveInstanceState() in SettingsActivity as they say here: topic
public class SettingsActivity extends android.support.v7.app.ActionBarActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
if (savedInstanceState != null) {
getFragmentManager()
.beginTransaction()
.add(R.id.seekBar_container, getFragmentManager().getFragment(savedInstanceState, AudioSamplingSeekBarFragment.TAG) , AudioSamplingSeekBarFragment.TAG)
.commit();
} else {
getFragmentManager()
.beginTransaction()
.add(R.id.seekBar_container, new AudioSamplingSeekBarFragment(), AudioSamplingSeekBarFragment.TAG)
.commit();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager()
.putFragment(outState, AudioSamplingSeekBarFragment.TAG, getFragmentManager().findFragmentByTag(AudioSamplingSeekBarFragment.TAG));
}
And save specific data in onSaveInstanceState() in Fragment:
public class AudioSamplingSeekBarFragment extends Fragment {
public static final String TAG = "SEEK_BAR_FRAGMENT_TAG";
public static final String STATE_FORMAT = "format";
private int format;
private int seekBarInitVal;
**#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_FORMAT, format);
}**
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_audio_sampling_seekbar, container,false);
}
And i'm expecting to restore saved data here:
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null) {
**format = savedInstanceState.getInt(STATE_FORMAT);**
} else if (getArguments() != null){
format = getArguments().getInt(STATE_FORMAT);
} else {
format = AAC;
}
SeekBar seekBar = (SeekBar)view.findViewById(R.id.sample_rate_seek_bar);
final TextView textProgress = (TextView) view.findViewById(R.id.progress);
switch (format) {
case AAC:
seekBarInitVal = 8000;
seekBar.setMax(40000);
break;
case AAC_ELD:
seekBarInitVal = 16000;
seekBar.setMax(32000);
break;
case AMR_NB:
seekBarInitVal = 8000;
seekBar.setEnabled(false);
break;
case AMR_WB:
seekBarInitVal = 16000;
seekBar.setEnabled(false);
break;
case HE_AAC:
seekBarInitVal = 8000;
seekBar.setMax(40000);
break;
}
textProgress.setText("" + seekBarInitVal + " Hz");
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
i += seekBarInitVal;
textProgress.setText("" + i + " Hz");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
But it doesn't work.
Just in case layouts:
activity_preference:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/preferences_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/seekBar_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
fragment_audio_sampling_seekbar:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/seekBar_fragment">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#dbdbdd" />
<TextView
android:id="#+id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:layout_marginTop="14dp"
android:text="Set Audio Sampling Rate"
android:textAppearance="#style/TextAppearance.AppCompat" />
<SeekBar
android:id="#+id/sample_rate_seek_bar"
android:layout_width="303dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/summary"
android:layout_marginTop="40dp" />
<TextView
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/summary"
android:layout_marginTop="66dp"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="96dp"
android:background="#dbdbdd" />
</RelativeLayout>
As far as I was aware, SavedInstanceState only stores a Bundle of data. Only basic things such as Strings, Integers etc. and does not hold anything like Views.
I think you should really use a ViewModel as it can hold data such as custom classes and views and keep them during orientations changes and are only lost once the Activity is destroyed.
Android View Models
You can then code in a more "permanent" storage option say using SharedPreferences, files, sqlite when the Activity is destroyed. The persisted data can then be fetched and populate the ViewModel in the onAttatch method.
Maybe have a read of this to determine your requirements:
Android - Saving UI states.

Load Preferences Settings in Swipable Tabs with Fragment

I have searched the web but didnt find any proper solution.
I am trying to load some preference Settings in Tab Fragments.
In the first Image, When I use menu Inflator, I get those 3 dotted buttons, I dont need those, insted I want the menu to load in my Tab Fragment.
Below is the code of my
SettingPrefActivity.java
public class SettingsPrefActivity extends AppPreferenceActivity {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// load settings fragment
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
}
public static class MainPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_main);
// gallery EditText change listener
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name)));
// notification preference change listener
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_notifications_new_message_ringtone)));
// feedback preference click listener
Preference myPref = findPreference(getString(R.string.key_send_feedback));
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
sendFeedback(getActivity());
return true;
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(R.string.summary_choose_ringtone);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else if (preference instanceof EditTextPreference) {
if (preference.getKey().equals("key_gallery_name")) {
// update the changed gallery name to summary filed
preference.setSummary(stringValue);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Email client intent to send support mail
* Appends the necessary device information to email body
* useful when providing support
*/
public static void sendFeedback(Context context) {
String body = null;
try {
body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
body = "\n\n-----------------------------\nPlease don't remove this information\n Device OS: Android \n Device OS version: " +
Build.VERSION.RELEASE + "\n App Version: " + body + "\n Device Brand: " + Build.BRAND +
"\n Device Model: " + Build.MODEL + "\n Device Manufacturer: " + Build.MANUFACTURER;
} catch (PackageManager.NameNotFoundException e) {
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact#androidhive.info"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Query from android app");
intent.putExtra(Intent.EXTRA_TEXT, body);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_email_client)));
}}
SettingsActivity.java
public class SettingsActivity extends Fragment {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
/*public SettingsActivity() {
// Required empty public constructor
}*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.setting_layout, container, false);
}
/*public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// launch settings activity
startActivity(new Intent(SettingsActivity.this, SettingsPrefActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
pref_main.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="General">
<EditTextPreference
android:defaultValue="#string/default_gallery_storage"
android:key="#string/key_gallery_name"
android:summary="#string/default_gallery_storage"
android:title="#string/title_gallery_storage" />
<CheckBoxPreference
android:defaultValue="true"
android:key="#string/key_upload_over_wifi"
android:summary="#string/summary_upload_over_wifi"
android:title="#string/title_auto_upload" />
<ListPreference
android:defaultValue="3"
android:dialogTitle="#string/title_upload_quality"
android:entries="#array/pref_upload_quality_entries"
android:entryValues="#array/pref_upload_quality_values"
android:key="#string/key_upload_quality"
android:summary="#string/summary_upload_video_quality"
android:title="#string/title_upload_quality" />
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_title_notifications">
<SwitchPreference
android:defaultValue="true"
android:key="#string/notifications_new_message"
android:title="#string/title_new_notification_sound" />
<RingtonePreference
android:defaultValue="content://settings/system/notification_sound"
android:dependency="notifications_new_message"
android:key="#string/key_notifications_new_message_ringtone"
android:ringtoneType="notification"
android:summary="#string/summary_choose_ringtone"
android:title="#string/pref_title_ringtone" />
<SwitchPreference
android:defaultValue="true"
android:key="#string/key_vibrate"
android:summary="#string/summary_vibrate"
android:title="#string/title_vibrate" />
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_header_about">
<Preference
android:selectable="false"
android:summary="#string/summary_about" />
<Preference
android:summary="#string/app_version"
android:title="#string/title_version" />
<Preference
android:key="#string/key_send_feedback"
android:summary="#string/summary_support"
android:title="#string/title_send_feedback" />
<!-- preference opens url in browser -->
<Preference
android:summary="#string/summary_faq"
android:title="#string/title_faq">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_faq" />
</Preference>
<Preference android:title="#string/privacy_policy">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_privacy" />
</Preference>
<Preference android:title="#string/title_terms">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_terms" />
</Preference>
</PreferenceCategory>
</PreferenceScreen>
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu 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"
tools:context="settings.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
settings_layout.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Settings Page!! Coming Soon!"
android:textSize="30dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {R.drawable.ic_action_name};
String[] tabTitle={"","All"};
int[] unreadCount={0,5,3,0,12,3,9,0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
setupTabIcons();
}
private View prepareTabView(int pos) {
View view = getLayoutInflater().inflate(R.layout.custom_tab,null);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
TextView tv_count = (TextView) view.findViewById(R.id.tv_count);
tv_title.setText(tabTitle[pos]);
if(unreadCount[pos]>0)
{
tv_count.setVisibility(View.VISIBLE);
tv_count.setText(""+unreadCount[pos]);
}
else
tv_count.setVisibility(View.GONE);
return view;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
/*TabLayout.Tab tabitem = tabLayout.newTab();
tabitem.setCustomView(prepareTabView(i));
tabLayout.addTab(tabitem);*/
for(int i = 1; i < unreadCount.length; i++)
{
/*TabLayout.Tab tabitem = tabLayout.newTab();
tabitem.setCustomView(prepareTabView(i));
tabLayout.addTab(tabitem);*/
tabLayout.getTabAt(i).setCustomView(prepareTabView(i));
}
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final
ViewPager viewPager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SettingsActivity(), "");
adapter.addFragment(new AllTab(), "All");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="inc.apperz.passmanager.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorGreen"
app:tabTextColor="#color/colorWhite"
app:tabIndicatorColor="#color/colorWhite"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.constraint.ConstraintLayout>
Is there any possibility that I can include my main_menu.xml into my setting_layout.xml? such that it will get bind to my SettingsActivity.java?
If its possible, that would be great, but I tried that way and didn't find appropriate way to include it.
Can someone guide me to how to achieve this..
Try adding this to your fragment:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}

notifyDataSetChanged stop working after onDestroy in fragment

I've got a fragment with a RecyclerView inside. All is working good but when I press home, navigate in other apps and then go back in my app the view gets recreated and my ArrayList (restored from onSaveInstanceState) is not displayed in my recyclerview that don't work even after updating the List.
Here some code:
-Activity
public class MainActivity extends AppCompatActivity {
FragmentTransaction ft;
BottomNavigationView bottomNavigationView;
int current;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState==null) {
setupFragment();
}
// mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottom_navigation);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_golden_hour:
changeFragment(new GoldenFragment(), "GOLDEN");
current=0;
break;
case R.id.action_hyperfocal:
changeFragment(new HyperFragment(), "HYPER");
current=1;
break;
case R.id.action_ir:
changeFragment(new IrFragment(), "IR");
current=2;
break;
case R.id.action_nd:
changeFragment(new NdFragment(), "ND");
current=3;
break;
}
return true;
}
});
}
#SuppressLint("CommitTransaction")
private void setupFragment(){
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.main_fragment, new GoldenFragment()).commit();
current=0;
}
#SuppressLint("CommitTransaction")
private void changeFragment(Fragment fragment, String tag){
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_fragment, fragment, tag).commit();
}
-Fragment
public class GoldenFragment extends Fragment implements DatePickerDialog.OnDateSetListener{
SupportPlaceAutocompleteFragment autocompleteFragment;
RecyclerView rv;
CustomAdapter adapter;
ProgressBar pb;
ArrayList<Hours> hours;
CardView cv;
TextView emptyGoldenText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
thisContext = getContext();
setHasOptionsMenu(true);
ampm = !android.text.format.DateFormat.is24HourFormat(thisContext);
hours = new ArrayList<>();
adapter = new CustomAdapter(thisContext, hours);
if(savedInstanceState!=null) {
Log.d(TAG,"inState not null");
hours.clear();
hours = savedInstanceState.getParcelableArrayList("HoursList");
}
Log.d(TAG,"onCreate() called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view == null) {
view = inflater.inflate(R.layout.fragment_golden, container, false);
}
Toolbar goldenToolbar = (Toolbar) view.findViewById(R.id.toolbar_golden);
((AppCompatActivity) getActivity()).setSupportActionBar(goldenToolbar);
emptyGoldenText = (TextView) view.findViewById(R.id.empty_golden_text);
autocompleteFragment = (SupportPlaceAutocompleteFragment) getChildFragmentManager()
.findFragmentById(R.id.place_autocomplete_fragment);
if (autocompleteFragment == null) {
autocompleteFragment = (SupportPlaceAutocompleteFragment) SupportPlaceAutocompleteFragment
.instantiate(thisContext, "com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment");
}
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.i(TAG, "Place: " + place.getName());
try {
new GeoCoding()
.execute("https://maps.googleapis.com/maps/api/geocode/json?address="+place.getName()+"&key="+geoKEY);
} catch (Exception e) {
Toast.makeText(thisContext,"Cannot contact Google's servers, please try later.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public void onError(Status status) {
Log.i(TAG, "An error occurred: " + status);
}
});
getChildFragmentManager().beginTransaction()
.replace(R.id.place_autocomplete_fragment, autocompleteFragment).commit();
//Initialize RecyclerView
rv = (RecyclerView)view.findViewById(R.id.list_golden);
rv.setLayoutManager(new LinearLayoutManager(thisContext));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(),
getActivity().getResources().getConfiguration().orientation);
rv.addItemDecoration(dividerItemDecoration);
rv.setAdapter(adapter);
cv = (CardView) view.findViewById(R.id.cv_golden);
pb = (ProgressBar) view.findViewById(R.id.progress_bar);
if(savedInstanceState==null) {
Log.d(TAG,"New empty data set");
rv.setVisibility(View.GONE);
cv.setVisibility(View.GONE);
pb.setVisibility(View.INVISIBLE);
}
else{
Log.d(TAG,"Old data set");
adapter.notifyDataSetChanged();
pb.setVisibility(View.INVISIBLE);
rv.setVisibility(View.VISIBLE);
cv.setVisibility(View.VISIBLE);
emptyGoldenText.setVisibility(View.INVISIBLE);
}
Log.d(TAG,"onCreateView() called");
return view;
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("HoursList",hours);
Log.d(TAG,"onSaveInstanceState called");
}
SOLVED
Solved by moving
adapter = new CustomAdapter(thisContext, hours);
from onCreate() to onCreateView().
In the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().
#Override
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "KEY");
changeFragment(fragment, "MY TAG")
} else {
setupFragment();
}
...
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Fragment fragment = getSupportFragmentManager().findFragmentByTag("MY TAG");
if (fragment != null) {
getSupportFragmentManager().putFragment(outState, "KEY", fragment);
}
}
try this code: in onSaveInstanceState put arraylist
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("HoursList",hours);
Log.d(TAG,"onSaveInstanceState called");
}
In onActivityCreated you check the following conditions:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState! = null) {
//probably orientation change
Log.d(TAG,"inState not null");
hours.clear();
hours = savedInstanceState.getParcelableArrayList("HoursList");
//check if u get the value print log
}
else {
if (hours != null) {
//returning from backstack, data is fine, do nothing
} else {
//newly created, compute data
hours = computeData();
}
}
}

Shared-preferences working just with Fragment Activity

I have this Fragment Activity which is my main activity and include 2 Fragment Activity.
/** SharedPreferences */
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
int currentOrientation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/** Rotation SharedPreferences */
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
int orienation = preferences.getInt("orientation", -1);
if (orienation != -1) {
setRequestedOrientation(orienation);
}
/** End */
mAdapter = new FragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (outState == null) {
outState = new Bundle();
}
outState.putInt("currentOrientation",
Integer.valueOf(currentOrientation));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentOrientation = savedInstanceState.getInt("currentOrientation");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menus, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
/** Rotation */
case R.id.menuRotate:
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = preferences.edit();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
editor.putInt("orientation",
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
editor.putInt("orientation",
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
editor.commit();
break;
}
return false;
}
}
I had set the orientation option in the menu.
The user can change the orientation from the menu to be in landscape or portrait.
Its working nice, BUT the problem is the other activities.
How can I read from the shared-preferences that I'v already declared in my main activity
what I want is that all activities in my app get the same orientation what the users choice from the menu.
This is one of my other activity:
public class MainList extends Activity {
LinearLayout b1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
b1 = (LinearLayout) findViewById(R.id.list_a);
b1.setOnClickListener(mb1);
}
View.OnClickListener mb1 = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainList.this, List_1.class));
}
};
Thanks in Advance :)
So, in each you should be using the same context and not just "this".
private Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
You can make this context accessible by other classes that do not have a type (just function holders).
Then, in your use of Shared Prefs :
final SharedPreferences prefList = context.getSharedPreferences(
Constants.PREFERENCE_NAME, Context.MODE_PRIVATE);
If everyone is using getApplicationContext() then they will be able to talk to one another as they are all using the same Context. I would always suggest that you use Context.MODE_PRIVATE unless you need external applications to be able to grab information from those SharedPreferences.

How to instantiate layout for custom preference, using android:layout attribute

I can set appropriate layout for preference through android:layout attribute. For an example
<Preference
android:key="friction"
android:title="#string/friction"
android:layout="#layout/friction_fragment"
android:shouldDisableView="true"
android:defaultValue="30"
android:enabled="true"
android:selectable="true"
android:summary="Bite friction">
</Preference>
where layout is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:text="#string/friction" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"></TextView>
<SeekBar android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="#+id/sbFriction"></SeekBar>
<TextView android:text="#string/friction_little" android:id="#+id/txtSummary" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:text="Button" android:id="#+id/btnFriction" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
I can get views in OnCreate in PreferenceActivity
Preference fric = (Preference)this.findPreference("friction");
View v = fric.getView(null, null);
SeekBar sbFriction = (SeekBar)v.findViewById(R.id.sbFriction);
sbFriction.setOnSeekBarChangeListener(this);
Button btnFric = (Button) v.findViewById(R.id.btnFriction);
btnFric.setOnClickListener(m_onClick);
but these events listeners, that I have set, are not fired.
How I can catch these events, for example - click from button.
Edit.
No, It did not fire any exception.
Here is more detailed code
public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener, OnSeekBarChangeListener
{
private TextView m_txtSummary;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference difficulty = (ListPreference)this.findPreference("difficulty");
difficulty.setSummary(difficulty.getEntry());
difficulty.setOnPreferenceChangeListener(this);
Preference fric = (Preference)this.findPreference("friction");
View v = fric.getView(null, null);
SeekBar sbFriction = (SeekBar)v.findViewById(R.id.sbFriction);
sbFriction.setOnSeekBarChangeListener(this);
Button btnFric = (Button) v.findViewById(R.id.btnFriction);
btnFric.setOnClickListener(m_onClick);
m_txtSummary = (TextView)v.findViewById(R.id.txtSummary);
fric.setSummary(fric.toString());
fric.setOnPreferenceChangeListener(this);
CheckBoxPreference music = (CheckBoxPreference)this.findPreference("music");
music.setOnPreferenceChangeListener(this);
}
private OnClickListener m_onClick = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.getId();
}
};
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue instanceof Boolean)
return true;
preference.setSummary(newValue.toString());
return true;
}
#Override
public void onProgressChanged(SeekBar v, int nProgress, boolean arg2) {
// TODO Auto-generated method stub
m_txtSummary.append(" " + nProgress);
m_txtSummary.invalidate();
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
//notifyChanged();
}
}
I'm not sure you are able to use a custom layout in conjunction with a PreferenceActivity in the way that you describe above.
I believe you should either:
Use a PreferenceScreen via addPreferencesFromResource() and implement classes like CheckBoxPreference, DialogPreference, and MultiSelectListPreference for the SharedPreferences items. (example)
or
Create a custom Activity (not PreferenceActivity) with custom layout (using setContentView()), and manually hook into the SharedPreferences using PreferenceManager.getDefaultSharedPreferences() editing them in the event listeners (View.onClickListener(), etc) using SharedPreferences.Editor .
Hope that makes sense.
Actually I found for an another solution. You could still use the Preferenceability:
Simply add a Fragment which calls the Custom Layout and add it’s class.
However you'll get a warning in the Manifest: (which you can ignore or fix)
[res] (AndroidManifest.xml)
android:name=".SettingsActivity_CUSTOMLAYOUT1"
"YOURPACKAGE.SettingsActivity_CUSTOMLAYOUT1 is not public"
It's only called from your SettingsActivity so you can ignore it
or
if you want to call this Activity from outside just create an own class for it and name it SettingsActivity_CUSTOMLAYOUT1.java.
CODE:
[java] (SettingsActivity.java)
public class SettingsActivity extends AppCompatPreferenceActivity {
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| YOURFRAGMENT1.class.getName().equals(fragmentName)
|| YOURFRAGMENT2.class.getName().equals(fragmentName)
|| CUSTOMLAYOUT1.class.getName().equals(fragmentName)
//... Add Fragments
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class YOURFRAGMENT1 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.YOURFRAGMENTXML1);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class YOURFRAGMENT2 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_private_data);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class FRAGMENTFORCUSTOMLAYOUT1 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(getActivity(), SettingsActivity.class));
startActivity(new Intent(getActivity(), CUSTOMLAYOUT1.class));
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
class SettingsActivity_CUSTOMLAYOUT1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CUSTOMLAYOUT1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
[xml] (pref_headers.xml)
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="YOURPACKAGE.SettingsActivity$YOURFRAGMENT1"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
<header
android:fragment="YOURPACKAGE.SettingsActivity$YOURFRAGMENT2"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
<header
android:fragment="YOURPACKAGE.SettingsActivity$CUSTOMLAYOUT1"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
</preference-headers>
[layout] (CUSTOMLAYOUT1.xml)
<?xml version="1.0" encoding="utf-8"?>
<...your custom layout>
Dont forget to add in Manifest.
[res] (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest>
<application
//Add activity
<activity
android:name=".SettingsActivity_CUSTOMLAYOUT1"
android:parentActivityName=".SettingsActivity">
</activity>
</application>
</manifest>

Categories

Resources