Introduction You might have noticed that in many Android apps, you need to tap the back button twice to exit. When you tap it once, a ...

Transitioning from Deprecated OnBackPressed in .NET MAUI Transitioning from Deprecated OnBackPressed in .NET MAUI

A blog about android developement

Introduction

You might have noticed that in many Android apps, you need to tap the back button twice to exit. When you tap it once, a message pops up. But if you tap it twice at the same time, you can close the app.


Before Android 13 (which is like the newest version), we used to make this work by changing how the back button behaves in the main part of the app (we call it "MainActivity"). But now, with Android 13, the way we used to do this is not recommended anymore. They have a new method that's better.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

  • This new method lets you see what will happen if you press the back button before you actually do it. This helps you decide if you want to go back or not. For example, you might choose to stay in the app, go back to the Home screen, or return to a previous page in a web browser.
  • To use this new method, Android 13 has added something called the "OnBackInvokedCallback". This is like a tool that helps you do this new back button behavior. It takes the place of the old way we used to change the back button behavior.
  • Now, instead of using the old way, we have the "OnBackPressedDispatcher" which takes care of handling when you press the back button. It works with the new method we just talked about.
  • class BackPress : OnBackPressedCallback
    {
    	private readonly Activity activity;
    	private long backPressed;
    
    	public BackPress(Activity activity) : base(true)
    	{
    		this.activity = activity;
    	}
    
    	public override void HandleOnBackPressed()
    	{
    		var navigation = Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation;
    		if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
    		{
    			const int delay = 2000;
    			if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
    			{
    				activity.FinishAndRemoveTask();
    				Process.KillProcess(Process.MyPid());
    			}
    			else
    			{
    				Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
    				backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    			}
    		}
    	}
    }
    
  • You'll want to take charge by overriding the HandleOnBackPressed method. The code inside this method closely resembles what you previously had in OnBackPressed.
  • In the last lap of this process, we're going to slot in this callback. You can achieve this by extending the OnCreate method of your MainActivity:
protected override void OnCreate(Bundle? savedInstanceState)
{
	base.OnCreate(savedInstanceState);
    OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
}

Full Code:

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
using AndroidX.Activity;

namespace MauiOnBackPressed;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
    }
}
class BackPress : OnBackPressedCallback
{
    private readonly Activity activity;
    private long backPressed;

    public BackPress(Activity activity) : base(true)
    {
        this.activity = activity;
    }

    public override void HandleOnBackPressed()
    {
        var navigation = Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation;
        if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
        {
            const int delay = 2000;
            if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
            {
                activity.FinishAndRemoveTask();
                Process.KillProcess(Process.MyPid());
            }
            else
            {
                Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
                backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            }
        }
    }
}

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and...

Flyout Page in .NET MAUI Flyout Page in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Flyout Page in .NET MAUI project.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

To create a flyout page in a Xamarin.Forms application, you can follow these steps:

  • Add a new page as AppFlyoutPage (XAML Flyout Page) and add the following code.
    <FlyoutPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:local="clr-namespace:MauiFlyoutPage"
                x:Class="MauiFlyoutPage.AppFlyoutPage">
        <FlyoutPage.Flyout>
            <local:MenuPage x:Name="flyoutPage" />
        </FlyoutPage.Flyout>
        <FlyoutPage.Detail>
            <NavigationPage>
                <x:Arguments>
                    <local:FirstPage />
                </x:Arguments>
            </NavigationPage>
        </FlyoutPage.Detail>
    </FlyoutPage>
  • Then create a content page "MenuPage" which will be used as master page and add the following code.
    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="MauiFlyoutPage.MenuPage"
                 Title="MenuPage">
        <VerticalStackLayout VerticalOptions="Center"
                             HorizontalOptions="Center">
            <Button 
                x:Name="btn"
                x:FieldModifier="public"
                Text="Open Second Page"
                VerticalOptions="Center" 
                HorizontalOptions="Center"/>
        </VerticalStackLayout>
    </ContentPage>
  • Open code behind and add the following code.
    namespace MauiFlyoutPage;
    
    public partial class AppFlyoutPage : FlyoutPage
    {
    	public AppFlyoutPage()
    	{
    		InitializeComponent();
            flyoutPage.btn.Clicked += OpenSecondPageClicked;
        }
    
        private void OpenSecondPageClicked(object sender, EventArgs e)
        {
            if (!((IFlyoutPageController)this).ShouldShowSplitMode)
                IsPresented = false;
            Detail = new NavigationPage(new SecondPage());
        }
    }
  • Here, "flyoutPage.btn" present in the master screen and accessed from the flyout screen using XAML field modifier."
  • In the same way, created two pages as "FirstPage" and "SecondPage" to navigate between the screens in the flyout menu.
  • Now, when we running the application, can able see a flyout menu on the left side and the detail content on the right side. Tapping on the button in the flyout master will update the detail content accordingly.

Full Code:

Demo

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

https://learn.microsoft.com/en-us/dotnet/maui/user-interface/pages/flyoutpage

Introduction .NET MAUI .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applicatio...

.NET MAUI Barcode Scanner using IRONBARCODE .NET MAUI Barcode Scanner using IRONBARCODE

A blog about android developement

Introduction

.NET MAUI

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


Using .NET MAUI, you have the capability to develop applications that can run on multiple platforms such as Android, iOS, MacOS, and Windows, all from a single codebase.


.NET MAUI allows for efficient cross-platform development, reducing the need for separate codebases for each platform and simplifying the maintenance and updates of your application.


.NET MAUI saves time and effort and makes it easier to maintain your apps. Visual Studio 2022 is avail with dotnet 7 with .Net Maui app development


In this article, we will see how we can implement a QR code or barcode scanner in the .NET MAUI project using IronBarcode Library.


IronBarcode: C# Barcode Library

The IronBarcode library simplifies barcode detection in .NET applications with its intuitive APIs and eliminates the need for intricate barcode object creation. It offers a wide range of QR code and barcode formats such as Code 39, Code 128, and PDF417.


As a versatile .NET library, it can also function as a QR code reader, decoding input data into readable text from various sources like images and streams. This article explores how to leverage the IronBarcode library for QR code scanning in .NET MAUI applications, providing a comprehensive guide.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Install IronBarcode Library

To install the IronBarcode library via the NuGet Packages Console, simply execute the following command or visit the Nuget package website or search in the Nuget package Manager to download the latest version of the library.

Install-Package BarCode

Implementation of File Picker functionality

Ironbarcode library will read the barcode from the selected image and provide the result. For File Picker functionality, visit the official .NET MAUI essentials link and set up all the mentioned steps in the link.

Designing the screen

In this tutorial, we are using Image, Button, and Editor controls. You can change the design as per your preferences.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MAUI_Barcode.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Editor x:Name="outputText"
                Placeholder="Output text"
                HeightRequest="100"
                WidthRequest="500"
                    />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Here,

  • Button - used to select barcode images that need to be read.
  • Image - used to display the selected barcode image.
  • Editor - used to display the scanned result from Iron Barcode Library.

Functionality of the screen

  • Add a click event for the button to select the image like below. This event will allow the app to select the barcode image.
    private async void SelectBarcode(object sender, EventArgs e)
    {
    	var images = await FilePicker.Default.PickAsync(new PickOptions
    	{
    		PickerTitle = "Pick Barcode/QR Code Image",
    		FileTypes = FilePickerFileType.Images
    	});
    	var imageSource = images.FullPath.ToString();
    	barcodeImage.Source = imageSource;
    	var result = BarcodeReader.Read(imageSource).First().Text;
    	outputText.Text = result;	
    }
  • Once the barcode image is selected, the File Picker will return the full path of the file.
  • We will assign the file path to the image control to preview the selected image.
  • As well as the selected image's file path will be sent as input to the barcode read library.
  • Once the input is processed, the library will return the scanned output as a result of the barcode read function. This output will be assigned to the editor control for displaying the result in human-readable text.

Full Code

using IronBarCode;

namespace MAUI_Barcode;

public partial class MainPage : ContentPage
{

	public MainPage()
	{
		InitializeComponent();
	}

	private async void SelectBarcode(object sender, EventArgs e)
	{
		var images = await FilePicker.Default.PickAsync(new PickOptions
		{
            PickerTitle = "Pick Barcode/QR Code Image",
            FileTypes = FilePickerFileType.Images
		});
		var imageSource = images.FullPath.ToString();
		barcodeImage.Source = imageSource;
		var result = BarcodeReader.Read(imageSource).First().Text;
		outputText.Text = result;
		
    }
}

Output

Upon selecting the barcode, the editor will display a screenshot similar to the one below, with the output text of the QR Code visible.

Before selecting the barcode, similar to other platforms as well:

After selecting the barcode:

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

Conclusion

This article detailed the process of barcode reading in a .NET MAUI application using IronBarcode. IronBarcode proves to be a comprehensive solution equipped with essential tools for barcode operations. Functioning as a QR code reader, IronBarcode delivers accurate and expected output, even when dealing with intricate barcodes. Furthermore, it offers the flexibility to create and customize barcodes using a variety of fonts.


IronBarcode is available for free for development purposes, but a license must be purchased for commercial use. To obtain information about the licensing options, please refer to the following link: https://ironsoftware.com/csharp/barcode/licensing

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and...

Dynamic Status Bar in .NET MAUI Dynamic Status Bar in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Dynamic Status Bar in .NET MAUI project.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

Screen Design:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 buttons like in the following code block.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiStatusBarBehaviour.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                Text="Blue"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnBlueClicked"
                HorizontalOptions="Center" />

            <Button
                Text="Green"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnGreenClicked"
                HorizontalOptions="Center" />

            <Button
                Text="Default"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnDefaultClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Methods:

To implement this, we can implement in the following methodlogies.

  • Applying Behaviour in XAML.
  • Applying Behaviour in Code behind.
  • Applying without behaviour in Code behind.

In this article, we are going to see "Applying without behaviour in Code behind.".

  • Just install the .NET MAUI community toolkit to your project.
    Install-Package CommunityToolkit.Maui -Version 3.1.0
  • Add it to the MauiProgram.cs
    var builder = MauiApp.CreateBuilder();
    builder
    .UseMauiApp<App>()
    .UseMauiCommunityToolkit()
    .ConfigureFonts(fonts => {
        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
    });
  • Add event in code behind for each button click and apply the below code.
    CommunityToolkit.Maui.Core.Platform.StatusBar.SetColor(statusBarColor);
    CommunityToolkit.Maui.Core.Platform.StatusBar.SetStyle(StatusBarStyle.LightContent);

Full Code:

Demo

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/statusbar-behavior

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and ...

Localisation in .NET MAUI Localisation in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Localisation in .NET MAUI project.


Advantages of Localisation

  • Localisation improves user experience by providing content and language that is culturally relevant and easily understandable to users in different regions, increasing engagement and satisfaction.
  • It expands market reach by making products or services accessible to a global audience, tapping into new markets and driving business growth.
  • Localisation helps build trust and credibility with international customers by demonstrating a commitment to their specific needs and preferences, fostering stronger relationships and customer loyalty.

Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

Screen Design:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 controls - 2 labels, and button like in the following code block.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:resource="clr-namespace:MauiLocalization"
             x:Class="MauiLocalization.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="{x:Static resource:LangResources.Helloworld}"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="{x:Static resource:LangResources.WelcomeNote}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Change to Tamil"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Create RESX file

In this step, we will see the steps to create RESX file.

  • In the Solution Explorer, right-click on the project or folder where you want to add the RESX file.
  • Select "Add" from the context menu and then choose "New Item" or "New Folder" if you want to organize your resources in a separate folder.
  • In the "Add New Item" dialog box, search for "Resource File" or navigate to "General" -> "Text File" and name the file with the .resx extension.
  • Click the "Add" button to create the resource file.
  • We created two resources file. One is default and another one prefixed with the language code.
    1. LangResources.resx
    2. LangResources.ta.resx (Contains the resource equivalent in tamil)

RESX Files in XAML

  • To utilize your resources, you first need to import the XML namespace associated with them.
  • xmlns:resource="clr-namespace:MauiLocalization"
  • Then, you can access your strings by using the [x:Static](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/xaml-markup-extensions#the-xstatic-markup-extension) markup extension, treating them as properties.
    Text="{x:Static resource:LangResources.Helloworld}"

Language Update

  • Add click event to the button to change language based on the language code of the resource file.
    private void OnCounterClicked(object sender, EventArgs e)
    {
    	if (CounterBtn.Text.Contains("Tamil"))
    	{
    		LangResources.Culture = new CultureInfo("ta");
    		CounterBtn.Text = "Change to English";
    	}
    	else
    	{
    		LangResources.Culture = CultureInfo.InvariantCulture;
    		CounterBtn.Text = "Change to Tamil";
    	}
    	App.Current.MainPage = new MainPage();
    }
  • Here, "App.Current.MainPage = new MainPage();" is used to refresh page once the language changed
  • Then, we will add the below block in the page constructor to retain the language change once the button clicked and page refreshed.
    if (LangResources.Culture != null && LangResources.Culture.TwoLetterISOLanguageName.Contains("ta"))
    {
    	CounterBtn.Text = "Change to English";
    }
    else
    {
    	CounterBtn.Text = "Change to Tamil";
    }

Full Code:

Demo

Android:

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

https://learn.microsoft.com/en-us/dotnet/core/extensions/resources

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C#...

File Picker in .NET MAUI File Picker in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement a File Picker in the .NET MAUI project.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 controls - button, image, and label like in the following code block.


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiFilePicker.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30"
            VerticalOptions="Start">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Label x:Name="outputText"
                   Padding="10"/>
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Here,

  • Button - used to select images from device.
  • Image - used to display the selected image.
  • Label - used to display the file path once the image selected through file picker.

Functional part

  • Add a click event for the button to select the image like below.
    private async void SelectBarcode(object sender, EventArgs e)
    {
    	var images = await FilePicker.Default.PickAsync(new PickOptions
    	{
    		PickerTitle = "Pick Barcode/QR Code Image",
    		FileTypes = FilePickerFileType.Images
    	});
    	var imageSource = images.FullPath.ToString();
    	barcodeImage.Source = imageSource;
    	outputText.Text = imageSource;
    }

    Here,

    • FileTypes: The default file types available for selection in the FilePicker are FilePickerFileType.Images, FilePickerFileType.Png, and FilePickerFileType.Videos. However, if you need to specify custom file types for a specific platform, you can create an instance of the FilePickerFileType class. This allows you to define the desired file types according to your requirements.
    • PickerTitle: The PickOptions.PickerTitle is presented to the user and its behavior varies across different platforms.

    Full Code:

    Demo

    Android:
    android
    Windows:
    windows

    Download Code:

    You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

    References

    https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/file-picker

.NET MAUI, a powerful platform for developing cross-platform mobile applications, provides a seamless way to incorporate Toast fun...

Toast in .NET MAUI Toast in .NET MAUI

A blog about android developement

.NET MAUI, a powerful platform for developing cross-platform mobile applications, provides a seamless way to incorporate Toast functionality into your app. With the aid of the appropriate tools and resources, implementing an Toast in .NET MAUI using the .NET MAUI Community Toolkit is a straightforward process. In this tutorial, we will guide you through the necessary steps to successfully integrate Toast into your .NET MAUI application.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

.NET MAUI Community Toolkit is the key to achieve drawing in our App is to use Community.ToolKit.Maui NuGet package. It is a collection of reusable elements such as animations, behaviors converters, among others, for developing applications for iOS, Android, macOS and WinUI using MAUI.


Install .NET MAUI Community Toolkit

  • Install .NET MAUI Community Toolkit nuGet package on your .NET MAUI application.
  • Now initialize the plugin. Go to your MauiProgram.cs file. In the CreateMauiApp method, place in the .UseMauiApp<App>() line and just below it add the following line of code.
var builder = MauiApp.CreateBuilder();
builder
	.UseMauiApp<App>()
	.UseMauiCommunityToolkit()
	.ConfigureFonts(fonts =>
	{
		fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
		fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	});
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            await Toast.Make("Hi, How are you?",
                      ToastDuration.Long,
                      16)
                .Show(cancellationTokenSource.Token);
  • The methods Make() and Show() are essential for displaying Toast messages on the screen. Each of these methods possesses specific attributes that facilitate the configuration of the Toast. Let's delve into a closer examination of these attributes.
  • Make:

    The Make() method is responsible for creating the Toast and requires the following parameters:
    • Text: This is a mandatory parameter represents the message that will be displayed in the Toast.
    • Duration: This parameter specifies the exact duration for which the Toast message will be shown on the screen before fading away. It is an optional parameter and it's default ToastDuration type is ToastDuration.Short:
    • TextSize: This parameter is an optional paramter to set the text size of the Toast. Default value of this parameter is 14 and it's type is double.

    Show:

    This method is responsible for displaying the requested Toast message on the screen.

    Full Code:

    Demo

    Download Code:

    You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

    The idea behind this tutorial is from "AskXammy"

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's eas...

Avatar View in .NET MAUI Community Toolkit Avatar View in .NET MAUI Community Toolkit

A blog about android developement

.NET MAUI is a powerful platform for building cross-platform mobile applications, and with the right tools and resources, it's easy to implement Avatar View to your app. In this tutorial, we'll walk you through the steps for adding Avatar View in .NET MAUI using .NET MAUI Community Toolkit.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation:

.NET MAUI Community Toolkit is the key to achieve drawing in our App is to use Community.ToolKit.Maui NuGet package. It is a collection of reusable elements such as animations, behaviors converters, among others, for developing applications for iOS, Android, macOS and WinUI using MAUI.


Install .NET MAUI Community Toolkit

  • Install .NET MAUI Community Toolkit nuGet package on your .NET MAUI application.
  • Now initialize the plugin. Go to your MauiProgram.cs file. In the CreateMauiApp method, place in the .UseMauiApp<App>() line and just below it add the following line of code.
var builder = MauiApp.CreateBuilder();
builder
	.UseMauiApp<App>()
	.UseMauiCommunityToolkit()
	.ConfigureFonts(fonts =>
	{
		fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
		fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
	});
  • A graphical representation known as an avatar is connected to a particular user in order to identify them. This is frequently utilised in programmes that we use every day, therefore it's crucial that you have access to the tools that will enable you to accomplish it. This tutorial will teach you how to quickly and easily construct the.NET Maui Community Toolkit AvatarView!
  • Add the following namespace in the xaml file.
    xmlns:toolkit="clr-namespace:CommunityToolkit.Maui.Views;assembly=CommunityToolkit.Maui"
  • Once the namespace added, you have to add the AvatarView tag with the properties that we required like below.
    <toolkit:AvatarView Text="AM"
    					FontSize="30"
                        TextColor="White"
                        BackgroundColor="Green"
                        BorderColor="White"
                        BorderWidth="5" 
                        HeightRequest="150"
                        WidthRequest="150"                                
                        CornerRadius="120"
                        ImageSource="dotnet_bot.png"/>
  • AvatarView’s properties

    • Text: This property help to set the text to the view
    • ImageSource: This property help to set the image to the view
    • CornerRadius: Determines the shape of the control. The properties can be set in the below ways.
    • Sample 1: CornerRadius="120"
    • Sample 2: CornerRadius="120,40,120,40"

    Full Code:

    Demo

    Download Code:

    You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.