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 :)
Related
I could display the map on my App interface , and now I'm trying to display a Pin of my current position .
I displayed in but with a button Click that shows me another Content Page . but I couldn't display it on the same page even after clicking that button .
If there's a way to show it , on the same page and without clicking any button , I'll be so thankful .
Here's the code of my Clicked_Button Event , This Code works and when I click it displays a new content page with my current position . but what I want it to to show it in my Map Module in the Main Page,
this is the XAML Code for my map (putting it in a grid):
<maps1:Map Grid.Column="1"
Grid.Row="2"
Grid.RowSpan="2"
Grid.ColumnSpan="3"
x:Name="myMap">
I tried to remove " Content = myMap; " from my back-end code to keep it on the main page , but the pin doesn't show up.
protected async void OnButtonClicked_speed(object sender, EventArgs args)
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
myMap = new Xamarin.Forms.Maps.Map(MapSpan.FromCenterAndRadius(
new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude),
Distance.FromMiles(0.5)))
{
IsShowingUser = true,
VerticalOptions = LayoutOptions.FillAndExpand
};
var position1 = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var pin1 = new Pin
{
Type = PinType.Place,
Position = position1,
Label = "Current Position",
Address = ""
};
myMap.Pins.Add(pin1);
Content = myMap;
}
Content = myMap
this is equivalent to repopulating your current page with a map
so you just move the code out of your OnButtonClicked_speed method.
like this:
in MainPage.xaml.cs
public partial class MainPage : ContentPage
{
private Map myMap;
public MainPage(Position position)
{
InitializeComponent();
myMap.MoveToRegion(MapSpan.FromCenterAndRadius(
new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude),
Distance.FromMiles(0.5)));
myMap.IsShowingUser = true;
myMap.VerticalOptions = LayoutOptions.FillAndExpand;
var position1 = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var pin1 = new Pin
{
Type = PinType.Place,
Position = position1,
Label = "Current Position",
Address = ""
};
myMap.Pins.Add(pin1);
}
public static async Task<MainPage> CreateMainPageAsync()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
MainPage page = new MainPage(position );
return page;
}
}
in App.xaml.cs
public partial class App : Application
{
public App()
{
InitializeComponent();
}
protected override async void OnStart()
{
namespace.MainPage main = await namespace.MainPage.CreateMainPageAsync();
MainPage = main;
}
}
im quite new to c# and Xamarin and I've just encountered a problem. I can't seem to be able to set the back button title on a navigation page. Ive tried using the static SetBackButtonTitle method but it does not seem to set the back button to the title I want which is
'Test' but instead its giving me the 'default' title which is "Back".
// The root page of your application
var content = new ContentPage();
var CompanyName = new Label();
CompanyName.HorizontalTextAlignment = TextAlignment.Center;
CompanyName.Text = "Test";
var NextPage = new Button();
NextPage.Text = "Next Page";
NextPage.Font = Font.SystemFontOfSize(NamedSize.Large);
NextPage.BorderWidth = 1;
NextPage.HorizontalOptions = LayoutOptions.Center;
NextPage.VerticalOptions = LayoutOptions.CenterAndExpand;
var layout = new StackLayout();
layout.VerticalOptions = LayoutOptions.CenterAndExpand;
layout.Children.Add(CompanyName);
layout.Children.Add(NextPage);
content.Content = layout;
var content2 = new ContentPage();
var navigation = new NavigationPage(content);
NavigationPage.SetHasBackButton(navigation,true);
NavigationPage.SetBackButtonTitle(navigation,"Test");
NextPage.Clicked += NextPageClicked;
async void NextPageClicked(object sender, EventArgs e)
{
await navigation.PushAsync(content2);
}
MainPage = navigation;
}
If you want to change the back button's title(at the left in the navigation bar) in the second page, you should call the method SetBackButtonTitle with first page as parameter. So please modify NavigationPage.SetBackButtonTitle(navigation,"Test"); to NavigationPage.SetBackButtonTitle(content,"Test");
For those who use Xamarin.Forms WPF if you want to change back button title you can do this:
protected override void OnDisappearing()
{
base.OnDisappearing();
Title = "";
}
protected override void OnAppearing()
{
base.OnAppearing();
Title = "MyTitle";
}
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 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();
}
}
I am building an app where user can select which Language he wants to set when the app starts. A pop up will show "Select your Language" with two buttons one for Arabic and the other one for English.
The problem is that when I change the locale and execute this line
SetContentView (Resource.Layout.Main);
the app broke. there is no error or any exception but all controls stop capturing the events. I tried to declare an Intent using this and this.Class and when I call StartActivity it is like restarting the whole app and the pop comes again to select the language. I am new to android development as I spent my last two years working on SAP Abap so I might ask a stupid question :D
here is my code
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Khums
{
[Activity (Label = "Khums", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
int r = Resource.Layout.Main;
SetContentView (Resource.Layout.Main);
var languageIso = "ar-SA";
AlertDialog.Builder alert = new AlertDialog.Builder (this);
//alert.SetTitle ("Selected Language");
AlertDialog alertDiaog = alert.Create ();
alertDiaog.SetTitle ("Select Language:");
alertDiaog.SetButton ("العربية", (s, EventArgs) => {
languageIso = "ar-SA";
var locale = new Java.Util.Locale(languageIso);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration{Locale = locale };
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
//base.SetContentView(r);
//Intent intent = new Intent(this, this.Class);
//StartActivity(intent);
SetContentView (Resource.Layout.Main);
});
alertDiaog.SetButton2 ("English", (s, EventArgs) => {
languageIso = "en-US";
var locale = new Java.Util.Locale(languageIso);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration{Locale = locale };
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
SetContentView (Resource.Layout.Main);
});
alertDiaog.Show();
Button button = FindViewById<Button> (Resource.Id.myButton);
RadioButton rb_FirstTime = FindViewById<RadioButton> (Resource.Id.radioButton1);
RadioButton rb_Regular = FindViewById<RadioButton> (Resource.Id.radioButton2);
EditText ti_lyearBalance = FindViewById<EditText> (Resource.Id.ti_lastBalance);
EditText ti_Balance = FindViewById<EditText> (Resource.Id.ti_Balance);
EditText ti_Clothes = FindViewById<EditText> (Resource.Id.ti_Clothes);
EditText ti_Food = FindViewById<EditText> (Resource.Id.ti_Food);
EditText ti_Perfumes = FindViewById<EditText> (Resource.Id.ti_Perfumes);
EditText ti_Subscriptions = FindViewById<EditText> (Resource.Id.ti_Subscriptions);
EditText ti_Others = FindViewById<EditText> (Resource.Id.ti_Others);
TextView lbl_lyearBalance = FindViewById<TextView> (Resource.Id.lbl_lastBalance);
rb_FirstTime.Click += RadioButtonHandler;
rb_Regular.Click += RadioButtonHandler;
button.Click += MyButtoHandler;
}
private void RadioButtonHandler(object sender, EventArgs e)
{
}
private void MyButtoHandler(object sender, EventArgs e)
{
}
private double calculateKhumus (double[] amounts, Boolean isRegular)
{
}
private void LangSwitchHndler(Object sender, EventArgs e)
{
}
}
}
can you please show me what I'm doing wrong here. I tried to use togglebutton instead of alert and also standard button but ends up with the same issue. Thank you.
It is solved after trying for two days. All I did is to create a menu and change the target framework to Android 3.1 Honeycomb. Then I just start the activity and everything is working fine.
So the issue was only target framework!