Reputation: 108
My android app will connect to the service url which pass the data and the data will be saved in my App data-variables and the working will start .So,I want the user to dynamically change the service url from the Settings menu if needed. If not then the default url must do its work. I have declared a variable in Resources/values/strings.xml file. But this is Static I want to make it dynamic. and the url must be set before the application starts I'm Working in Visual Studio 2017 With Xamarin Android.
Upvotes: 2
Views: 125
Reputation: 10831
So,I want the user to dynamically change the service url from the Settings menu if needed. If not then the default url must do its work.
You can use Preferences to achieve that:
Example:
Create a preferences.xml
in Resouces\xml
to hold the settings:
<?xml version="1.0" encoding="utf-8" ?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="pref_url"
android:title="pref_url"
android:summary="This is service url"
//default value for url service setting
android:defaultValue="http://www.google.com" />
</PreferenceScreen>
Create a SettingsFragment
and SettingsActivity
as container of the setting:
public class SettingsFragment:PreferenceFragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
AddPreferencesFromResource(Resource.Xml.Preferences);
}
public override void OnResume()
{
base.OnResume();
PreferenceScreen.SharedPreferences.RegisterOnSharedPreferenceChangeListener(this);
}
public override void OnPause()
{
base.OnPause();
PreferenceScreen.SharedPreferences.UnregisterOnSharedPreferenceChangeListener(this);
}
}
[Activity(Label = "PreferenceDemo")]
public class SettingsActivity:Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Settings);
FragmentManager.BeginTransaction().Replace(Resource.Id.container, new SettingsFragment()).Commit();
}
}
Get the setting from anywhere in your app:
ISharedPreferences sharedPref = PreferenceManager.GetDefaultSharedPreferences(this);
string syncConnPref = sharedPref.GetString("pref_url", "");
Here is the complete Demo:PreferenceDemo.
Upvotes: 1