Menu is created, but disappears after navigations - xamarin

I created menu in Xamarin Android application. It is showing on first page, but after PushAsync it disappears. Also after returning to first page it is not showing any more. Here is a code:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IOnMenuItemClickListener
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.InflateMenu(Resource.Menu.action_menu);
toolbar.SetOnMenuItemClickListener(this);
}
public bool OnMenuItemClick(IMenuItem item)
{
...
return true;
}
}
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
public partial class MainPage : ContentPage
{
...
private async void OnSecondPageClicked()
{
await Navigation.PushAsync(new SecondPage());
}
}
File action_menu.xml:
<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/item1"
android:title="new_game"
android:showAsAction="always"/>
<item android:id="#+id/item2"
android:title="help"
android:showAsAction="always"/>
</menu>

You have a mixture of a Xamarin.Android app and a Xamarin.Forms app. This answer assumes you want a forms app. You should remove the following lines from OnCreate
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.InflateMenu(Resource.Menu.action_menu);
toolbar.SetOnMenuItemClickListener(this);
And add these lines to the constructor of MainPage
this.ToolbarItems.Add(new ToolbarItem("New Game", "", () => { }));
this.ToolbarItems.Add(new ToolbarItem("Help", "", () => { }));
If that works you should move MainPage and App into your Cross Platform project.

Related

Exception : System.NullReferenceException: 'Object reference not set to an instance of an object.'

I'm trying to create a simple Qr code scanner application who have a single view like this:
But when I tried to press the "CLICK" button to lunch the scanner I got this excption:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
this is the main.xaml page:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="scanner.MainPage">
<StackLayout Spacing="10">
<Button Text="Click"
x:Name="btnScan"
Clicked="btnScan_Clicked"/>
<Entry x:Name="txtBarcode"
Placeholder="Text Do scan"/>
</StackLayout>
</ContentPage>
the main.xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void btnScan_Clicked(object sender, EventArgs e)
{
try
{
var scanner = DependencyService.Get<Interface1>();
var result = await scanner.ScanAsync();
if (result != null)
{
txtBarcode.Text = result;
}
}
catch (Exception ex)
{ throw;
}
the service:
internal class QrScanningService : Interface1
{
public async Task<string> ScanAsync()
{
var optionsDefault = new MobileBarcodeScanningOptions();
var optionsCustom = new MobileBarcodeScanningOptions();
var scanner = new MobileBarcodeScanner()
{
TopText = "Scan the QR Code",
BottomText = "Please Wait",
};
var scanResult = await scanner.Scan(optionsCustom);
return scanResult.Text;
}
}
I had done a simple and meet the same problem. So I searched it on the internet and found that the plugin need to be initialized when you use the ZXing.Net.Mobile package.
So you can add the initialized code in to the OnCreate method of the MainActivity. Such as:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
MobileBarcodeScanner.Initialize(Application);// this line initialize the plugin
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
You can check the document about it :https://github.com/Redth/ZXing.Net.Mobile#android
And on the ios check this link:https://github.com/Redth/ZXing.Net.Mobile#ios

How to achieve a popup which contain data filters

I have a popup in which I have a List of Filters, So when select on the filter the data should populate based on filter.This is the Image I need to develop
You can use Rg.Plugins.Popup from nuget .
in iOS
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Rg.Plugins.Popup.Popup.Init();
global::Xamarin.Forms.Forms.Init ();
LoadApplication (new App ());
return base.FinishedLaunching (app, options);
}
}
in Android
namespace HelloXamarinFormsWorld.Android
{
[Activity(Label = "HelloXamarinFormsWorld", MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Rg.Plugins.Popup.Popup.Init(this, bundle);
Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication (new App ());
}
}
}
Usage
Create a subclass of
in xaml
<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
x:Class="xxx.MyPopupPage">
<!--You can set an animation in the xaml file or in the csharp code behind-->
<pages:PopupPage.Animation>
<animations:ScaleAnimation
PositionIn="Center"
PositionOut="Center"
ScaleIn="1.2"
ScaleOut="0.8"
DurationIn="400"
DurationOut="300"
EasingIn="SinOut"
EasingOut="SinIn"
HasBackgroundAnimation="True"/>
</pages:PopupPage.Animation>
<!--You can use any elements here which are extended from Xamarin.Forms.View-->
<StackLayout >
<Listview>
// You can load the data here
</Listview>
</StackLayout>
</pages:PopupPage>
in code behind
public partial class MyPopupPage : Rg.Plugins.Popup.Pages.PopupPage
{
public MyPopupPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
}
// ### Methods for supporting animations in your popup page ###
// Invoked before an animation appearing
protected override void OnAppearingAnimationBegin()
{
base.OnAppearingAnimationBegin();
}
// Invoked after an animation appearing
protected override void OnAppearingAnimationEnd()
{
base.OnAppearingAnimationEnd();
}
// Invoked before an animation disappearing
protected override void OnDisappearingAnimationBegin()
{
base.OnDisappearingAnimationBegin();
}
// Invoked after an animation disappearing
protected override void OnDisappearingAnimationEnd()
{
base.OnDisappearingAnimationEnd();
}
protected override Task OnAppearingAnimationBeginAsync()
{
return base.OnAppearingAnimationBeginAsync();
}
protected override Task OnAppearingAnimationEndAsync()
{
return base.OnAppearingAnimationEndAsync();
}
protected override Task OnDisappearingAnimationBeginAsync()
{
return base.OnDisappearingAnimationBeginAsync();
}
protected override Task OnDisappearingAnimationEndAsync()
{
return base.OnDisappearingAnimationEndAsync();
}
// ### Overrided methods which can prevent closing a popup page ###
// Invoked when a hardware back button is pressed
protected override bool OnBackButtonPressed()
{
// Return true if you don't want to close this popup page when a back button is pressed
return base.OnBackButtonPressed();
}
// Invoked when background is clicked
protected override bool OnBackgroundClicked()
{
// Return false if you don't want to close this popup page when a background of the popup page is clicked
return base.OnBackgroundClicked();
}
}
For more details you can check https://github.com/rotorgames/Rg.Plugins.Popup/wiki/Getting-started

What did I do wrong on setting up MvvmCross 6.0?

I am new to MvvmCross 6.0 and Xamarin.
I am trying to follow the tutorial here that for MvvmCrosss 5.5
I followed the explanation,
Created App.xaml as MvxFormsApplication
<?xml version="1.0" encoding="utf-8" ?>
<core:MvxFormsApplication xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:core="clr-namespace:MvvmCross.Forms.Core;assembly=MvvmCross.Forms"
x:Class="App3.App">
</core:MvxFormsApplication>
CoreApp.cs as MvxApplication and runs RegisterAppStart(); in my overrided Initialize()
public class CoreApp : MvxApplication
{
public override void Initialize()
{
CreatableTypes()
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
CreatableTypes()
.EndingWith("Client")
.AsInterfaces()
.RegisterAsLazySingleton();
// register the appstart object
RegisterAppStart<MainPageViewModel>();
}
}
MainPageViewModel to inherited MvxViewModel
public class MainPageViewModel : MvxViewModel
{
}
View that created as MvxContentPage with type MainPageViewModel
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="Center"
HorizontalOptions="Center" />
Removed MainActivity and created a file called MainApplication.cs as follow
[Activity(Label = "MvvmcrossGettingStarted", Icon = "#drawable/icon", Theme = "#style/MainTheme", MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize |
ConfigChanges.Orientation)]
public class MainActivity : MvxFormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
var startup = Mvx.Resolve<IMvxAppStart>();
startup.Start();
InitializeForms(bundle);
}
}
public class Setup : MvxFormsAndroidSetup
{
public Setup():base()
{
}
protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies
.Union(new[] { typeof(App).GetTypeInfo().Assembly })
.Except(new[] { this.GetType().Assembly })
);
protected override Application CreateFormsApplication()
{
return new App();
}
protected override IMvxApplication CreateApp() => new CoreApp();
}
However what I started the app, its gives me null exception saying "bundle" parameter is null in OnCreated method.
P.S. The tutorial mention to create the Setup.cs, but I have no idea how does that Setup.cs being run by the code.... I see no where that is referencing it.
I'm not sure why you're looking at the version 5.5 tutorial while working with v 6.0. Try following step by step guide, from same author, but for version 6.0
You might also want to download Nick's sample, from his GitHub repo, to check how things work.

How to navigate deeper inside a xamarin detailpage

I have a project with a MasterDetailPage as root page. When I navigate deeper inside the Detailpage, I have the problem, that the DetailPage navigation overrides my actionbar for the MasterPage. Can I have both in the actionbar, the burgermenuicon and the backbutton?
before navigation:
after navigation:
public partial class MasterPage : MasterDetailPage
{
public MasterPage()
{
Master = SetMasterContentPage();
Detail = new NavigationPage(new TaxonomyOverviewPage());
}
ContentPage SetMasterContentPage()
{
var masterPage = new ContentPage { Title = "Test"};
masterPage.Content = new StackLayout
{
Children = {
new Label{Text="Label1"},
new Label{Text="Label2"},
new Label{Text="Label3"}
}
};
return masterPage;
}
protected override void OnAppearing()
{
base.OnAppearing();
}
}
Problem is solved.
I used a public static MasterDetailPage and referenced it to the MainPage in App.cs. Now I can access the IsPresented property of the MasterDetailPage.
public partial class App : Application
{
public static MasterPage masterdetail;
public App()
{
InitializeComponent();
}
protected override void OnStart()
{
masterdetail = new MasterPage();
Device.BeginInvokeOnMainThread(() => {
MainPage = masterdetail;
});
}
}
Finally, I add a menuicon to the right side of the actionbar.
protected override void OnAppearing()
{
base.OnAppearing();
ToolbarItems.Add(new ToolbarItem("Menu", "menuicon.png", () => { App.masterdetail.IsPresented = true; }));
}

Xamarin forms splash screen issue

A black screen with app title is showing when minimizing the app while loading splash screen , also the first screen will display after some time. Here is my splash activity and main activity classes.
[Activity(Theme = "#style/Theme.Splash", Icon = "#drawable/icon", MainLauncher = true, NoHistory = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation,
ScreenOrientation = ScreenOrientation.Behind)]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
var dpWidth = Resources.DisplayMetrics.WidthPixels/Resources.DisplayMetrics.Density;
RequestedOrientation = dpWidth > 700 ? ScreenOrientation.Unspecified : ScreenOrientation.Portrait;
ThreadPool.QueueUserWorkItem(o => LoadActivity());
}
private void LoadActivity()
{
RunOnUiThread(() => StartActivity(typeof(MainActivity)));
}
public override void OnBackPressed()
{
Environment.Exit(0);
}
}
[Activity(Label = "HACCP", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
ActionBar.SetIcon(Android.Resource.Color.Transparent);
Forms.Init(this, bundle);
// some function //
LoadApplication(new App());
}
}
You tagged Xamarin.Forms so it should be as simple as..
class App : Application
{
public App()
{
MainPage = new MySplashPage();
}
}
class MySplashPage : ContentPage
{
public MySplashPage()
{
Task.Delay(3000); //show my pretty splash for 3 seconds
Application.Current.MainPage = new MyOtherSpiffyPage();
}
}
Not certain if the activity attribute ScreenOrientation = ScreenOrientation.Behind) is causing any issues, we don't use that in our apps.
Here is a "standard" splash activity we do use, letting Xamarin.Android take care of timing etc:
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Start main.
StartActivity(typeof(MainActivity));
}
}
You might try simplifying your app in similar fashion.

Resources