I am new on xamarin and i am trying to save my checkbox state even if the app is closed because when i close it the checkbox reset to uncheck state...
also.. the image that was changed resets.. is there any way to preserve both?
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout1);
var seletor = FindViewById<CheckBox>(Resource.Id.checkBox1);
var imagem = FindViewById<ImageView>(Resource.Id.imageView1);
seletor.Click += (o, e) => {
if (seletor.Checked)
imagem.SetImageResource(Resource.Drawable.estado1);
else
imagem.SetImageResource(Resource.Drawable.estado2);
};
}
Have you tried to use the Preferences?
Check the following: How to save user settings
Store the option selected onclose or suspend.. and retrieve onResume / OnLoad
Something like:
// Function called from OnDestroy
protected void saveset(){
//store
var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
var prefEditor = prefs.Edit();
prefEditor.PutString("PrefName", "Some value");
prefEditor.Commit();
}
// Function called from OnCreate
protected void retrieveset()
{
//retreive
var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
var somePref = prefs.GetString("PrefName", null);
//Show a toast
RunOnUiThread(() => Toast.MakeText(this, somePref, ToastLength.Long).Show());
}
as in the link provided.
Of course you'll need to adapt to your needs and get / populate the value of the checkbox.
If you want, you can also implement some kind of db and use the same mechanism to persist and retrieve settings.
This is usually what I use to store settings and persist values that I need to "remember"
This is an example of how I'm using the same behavior in one app.. not for a checkbox.. but you can see how it works. I removed some code, but I think should be a good example.
[Activity(Label = "#string/ApplicationName",
Icon = "#drawable/Icon")]
public class PersonalDetailsActivity : Activity
{
...
private ISharedPreferencesEditor prefEditor;
private ISharedPreferences preferences;
...
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.PersonalDetailView);
preferences = Application.Context.GetSharedPreferences("AppName", FileCreationMode.Private);
PopulatePersistedData();
}
private void PopulatePersistedData()
{
myId = preferences.GetInt(nameof(myData.Id), 0);
name.Text = preferences.GetString(nameof(myData.Name), null);
address.Text = preferences.GetString(nameof(myData.Address), null);
city.Text = preferences.GetString(nameof(myData.City), null);
county.Text = preferences.GetString(nameof(myData.County), null);
emailAddress.Text = preferences.GetString(nameof(myData.Email), null);
phoneNumber.Text = preferences.GetString(nameof(myData.PhoneNumber), null);
bio.Text = preferences.GetString(nameof(myData.Bio), null);
rating.Rating = 5;
}
private void SaveButton_Click(object sender, EventArgs e)
{
prefEditor = preferences.Edit();
myData = new Citizen();
myData.Name = name.Text;
myData.Address = address.Text;
myData.City = city.Text;
myData.County = county.Text;
myData.Email = emailAddress.Text;
myData.PhoneNumber = phoneNumber.Text;
myData.Bio = bio.Text;
prefEditor.PutInt(nameof(myData.Id), myId);
prefEditor.PutString(nameof(myData.Name), myData.Name);
prefEditor.PutString(nameof(myData.Address), myData.Address);
prefEditor.PutString(nameof(myData.City), myData.City);
prefEditor.PutString(nameof(myData.County), myData.County);
prefEditor.PutString(nameof(myData.Email), myData.Email);
prefEditor.PutString(nameof(myData.PhoneNumber), myData.PhoneNumber);
prefEditor.PutString(nameof(myData.Bio), myData.Bio);
prefEditor.Apply();
prefEditor.Commit();
var intent = new Intent();
intent.PutExtra("CitizenName", name.Text);
SetResult(Result.Ok, intent);
this.Finish();
}
}
Related
ex: first time: i put 18001090 and i receive : 18001090
second time: i put 056113 but i receive : 18001090
I put extra
Intent notificationIntent = new Intent(context, typeof(MainActivity));
notificationIntent.SetAction("android.intent.action.MAIN");
notificationIntent.PutExtra("number", incomingNumber);
On MainActivity
var number = this.Intent.GetStringExtra("number");
I use Intent to put extra and get extra, but I don't get the result as you, here is my code.
I add EditText and Button on layout5 and TextView on layout6.
Mainactivity:
private EditText edittext;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout5);
btn1 = FindViewById<Button>(Resource.Id.button1);
edittext = FindViewById<EditText>(Resource.Id.edittext1);
btn1.Click += Btn1_Click1;
}
private void Btn1_Click1(object sender, EventArgs e)
{
Intent i = new Intent(this, typeof(Activity1));
//Add PutExtra method data to intent.
i.PutExtra("Name", edittext.Text.ToString());
//StartActivity
StartActivity(i);
}
Avtivity1:
private TextView text;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout6);
// Create your application here
string name = Intent.GetStringExtra("Name");
text = FindViewById<TextView>(Resource.Id.textview1);
text.Text = name;
Log.Debug("123" ,name);
}
I am on the most current version of Xamarin Forms. I have a Content Page. The Content Page has a content that has a Button. That Button has Button_Clicked event Which you can see below. I use IToastNitificator (https://github.com/EgorBo/Toasts.Forms.Plugin), and I try to pass when I send this notification after I close my app, and after I clicked the Notification my App doesn't pop up Again. Anybody can help me how can I reach this?
This is my Button_Clicked method:
private async void Button_Clicked(object sender, EventArgs e)
{
var notificator = DependencyService.Get<IToastNotificator>();
var options = new NotificationOptions()
{
Title = "Teszt",
Description = "Önnek teszteket kell kitöltenie!",
IsClickable = true
};
var result = await notificator.Notify(options);
if(result.Action == NotificationAction.Clicked)
{
await Navigation.PushAsync(new QuestionPage());
}
}
I registered this Dependency and It's working fine.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate (Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate (bundle);
Xamarin.Forms.DependencyService.Register<ToastNotification>();
Xamarin.Forms.DependencyService.Register<OpenAppAndroid>();
ToastNotification.Init(this);
BluetoothLowEnergyAdapter.Init(this);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new Spirocco.App (BluetoothLowEnergyAdapter.ObtainDefaultAdapter(ApplicationContext)));
}
}
To reopen the Android application you need to set the ForceOpenAppOnNotificationTap to true in the AndroidOptions
Example:
var options = new NotificationOptions()
{
Title = "Teszt",
Description = "Önnek teszteket kell kitöltenie!",
IsClickable = true,
AndroidOptions = new AndroidOptions()
{
ForceOpenAppOnNotificationTap = true
}
};
I'm building a xamarin app where I'm using a Preprocessed Razor Template as a webview. I used this guide to set it up: https://developer.xamarin.com/guides/cross-platform/advanced/razor_html_templates/
It's working great and all but every time I do some css changes I have to restart the app to see the css changes. Is there another way to do this so I don't have to restart the app every time?
I tried adding a button which reloads the webView but that did not work. This is my activity:
public class ItemWebViewActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var itemId = Intent.GetIntExtra("itemId", 0);
SetContentView(Resource.Layout.ItemWebView);
webView = FindViewById<WebView>(Resource.Id.webView);
var dataService = new AzureDataService();
var item = dataService.GetItem(itemId);
Button refreshButton = (Button)FindViewById(Resource.Id.refreshButton);
refreshButton.Click += ReloadPage;
var decodedDesc = WebUtility.HtmlDecode(item.Description);
var vm = new Item()
{
Artist = item.Artist,
Title = item.Title,
Picture = item.Picture,
Description = decodedDesc
};
var template = new ItemWebView() { Model = vm };
var page = template.GenerateString();
webView.LoadDataWithBaseURL("file:///android_asset/",page, "text/html", "charset=UTF-8",null);
}
private void ReloadPage(object sender, EventArgs e)
{
webView.Reload();
}
}
Would appreciate any help :)
I'm new to the Xamarin world, so I'm in a real need of your help. In my very first application I want to associate a progress bar with a button. So that when I click the button the progress bar starts and when the progress ends the progress bar disappears.
Here is my C# code:
translateButton.Click += (object sender, EventArgs e) =>
{
ProgressBar pb = FindViewById<ProgressBar>(Resource.Id.progressBar1);
Thread.Sleep(1000);
pb.Enabled = true;
translateNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (string.IsNullOrWhiteSpace(translateNumber))
{
callButton.Text = "Call";
callButton.Enabled = false;
pb.Enabled = true;
}
else
{
callButton.Text = "Call" + translateNumber;
callButton.Enabled = true;
pb.Enabled = true;
}
};
this code from this tutorial on Xamarin website.
Try something like this :
ProgressBar pb;
Button translateButton;
EditText phoneNumberText;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
translateButton = FindViewById<Button>(Resource.Id.translateButton);
phoneNumberText = FindViewById<EditText>(Resource.Id.phoneNumberText);
pb = FindViewById<ProgressBar>(Resource.Id.pb);
pb.Visibility = ViewStates.Invisible;
translateButton.Click += translateButtonClicked;
}
async void translateButtonClicked (object sender, EventArgs e)
{
pb.Visibility = ViewStates.Visible;
await myMethod();
pb.Visibility = ViewStates.Gone;
}
async Task myMethod()
{
await Task.Run(() => {
//
// Do the work stuff here
//
});
}
From MainActivity.cs to AnotherActivity.cs
public static string hisname;
public static string hername;
private Handler mHandler = new Handler();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Register1);
// Create your application here
EditText her = FindViewById<EditText>(Resource.Id.editTextHername);
EditText his = FindViewById<EditText>(Resource.Id.editTextUrname);
//RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
//anim.setInterpolator
//anim.setRepeatCount(Animation.INFINITE);
//anim.Duration(700);
//splash.StartAnimation(anim);
WindowRotationAnimation q = new WindowRotationAnimation();
Button getStarted = FindViewById<Button>(Resource.Id.myButton);
getStarted.Click += delegate
{
var intent = new Intent(this, typeof(CalculateActivity));
intent.PutExtra("yourname", ""+hisname);
intent.PutExtra("GFname", "" + hername);
StartActivity(intent);
};
}
}
Try with following
var herName = her.text;
vad hisName = his.text;
and add into intent.putextra method.
public static string hisname;
public static string hername;
private Handler mHandler = new Handler();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Register1);
// Create your application here
EditText her = FindViewById<EditText>(Resource.Id.editTextHername);
EditText his = FindViewById<EditText>(Resource.Id.editTextUrname);
//RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
//anim.setInterpolator
//anim.setRepeatCount(Animation.INFINITE);
//anim.Duration(700);
//splash.StartAnimation(anim);
WindowRotationAnimation q = new WindowRotationAnimation();
Button getStarted = FindViewById<Button>(Resource.Id.myButton);
getStarted.Click += delegate
{
hisname=his.Text;
hername=her.Text;
var intent = new Intent(this, typeof(CalculateActivity));
intent.PutExtra("yourname", hisname);
intent.PutExtra("GFname", hername);
StartActivity(intent);
};
}
inside your OnCreate of the AnotherActivity.cs you can get these strings like this:
string hisname=Intent.GetStringExtra ("yourname");
string hername=Intent.GetStringExtra ("GFname"); // Seriously :P
This is actually an easy solution if you wanted this one. I would suggest you should research first before you post questions
Happy Coding
pass data from your_first_activity to your_next_activity
Intent i = new Intent (Application.Context, typeof(your_next_activity));
i.PutExtra ("item", "item_to_pass");
StartActivity (i);
retrieve data bundle passed from your_first_activity on your_next_activity
string item = Intent.GetStringExtra("item");