Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 91519 articles
Browse latest View live

Content of a frame that is the View of a ViewCell appear on top of other rows in the list - iOS only


Device.RuntimePlatform not resolved in some files

$
0
0

Hi,

When using the RuntimePlatform attribute in some files, the VS cannot resolve the symbol. I have grouped my code in two folders (called "Misc" and "Models").

  1. Inside the Models directory, the Device.RuntimePlatform is found and works as expected.

  2. Inside the Misc directory (manually created by me), I get "The name 'Device.RuntimePlatform' does not exist in the current context." and the "using Xamarin.Forms" statement stays greyed out.

The Xamarin.Forms."Device" assembly is present and the RuntimePlatform attribute is there.

May you please advise how to figure this out?

On Platform values for font ionicons.woff

$
0
0

Hi

I am using custom font ionicons.woff and have used below;

    <ResourceDictionary>
        <OnPlatform x:TypeArguments="x:String" x:Key="ionicons">
            <On Platform="Android"
              Value="ionicons.woff#Regular" />
            <On Platform="iOS"
              Value="ioniconsr" />
        </OnPlatform>
    </ResourceDictionary>

However this is not working. What are the correct 'On Platform' values for font ionicons.woff and in general what is the method to get these values for a given font.

Thanks

Regards

Binding Library Error: How to make a method return an array of IDictionary ?

$
0
0

I am getting an error when I import a .aar file to integrate with a machine service.

My question is as per the title.

This the code I am trying to get:

[Register ("getSlots", "()[Ljava/util/HashMap;", "")]
        public unsafe global::System.Collections.Generic.IDictionary <string, byte[]> [] GetSlots ()
        {
            const string __id = "getSlots.()[Ljava/util/HashMap;";
            try {
                var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
                return (global::System.Collections.Generic.IDictionary<string, byte[]>[]) JNIEnv.GetArray (__rm.Handle, JniHandleOwnership.TransferLocalRef, typeof (global::System.Collections.Generic.IDictionary<string, byte[]>));
            } finally {
            }
        }

This is the code I am getting:

[Register ("getSlots", "()[Ljava/util/HashMap;", "")]
        public unsafe global::System.Collections.Generic.IDictionary <string, byte[]>GetSlots ()
        {
            const string __id = "getSlots.()[Ljava/util/HashMap;";
            try {
                var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
                return (global::System.Collections.Generic.IDictionary<string, byte[]>[]) JNIEnv.GetArray (__rm.Handle, JniHandleOwnership.TransferLocalRef, typeof (global::System.Collections.Generic.IDictionary<string, byte[]>));
            } finally {
            }
        }

I need a method that returns an array IDictionary <string, byte[]>[], but I am getting IDictionary <string, byte[]>

This is the code that is in metadata.xml

<attr path="/api/package[@name='br.com.uol.pagseguro.plugpagservice.wrapper']/class[@name='PlugPagNFCResult']/method[@name='getSlots' and count(parameter)=0]" name="managedReturn">System.Collections.Generic.IDictionary &lt;string, byte[]&gt;</attr>

But every time I write "[]", after ">", it doesn't appear to form an array!

Could you help me with this?

Create Multiple Table with SQLite Database

$
0
0

hello, xamarians,
I am creating a project and I want to need to more than 3 tables but I don't understand how to create
please help me out.

AppThemeBinding not working

$
0
0

Hi,
Using latest Xamarin Forms 4.7.0.968.
SfButton.BackgroundColor="{AppThemeBinding Light={StaticResource PrimaryColorLight}, Dark={StaticResource PrimaryColorDark }}"
is not working.
Thank you

Unable to get password autofill effect to work

$
0
0

I am developing a Xamarin.Forms app for iOS and Android. So far i only tested on iOS since that is the client priority.

i have followed the guide here to setup the password autofill but it does not seems to work. I follow the guide till the Domain association section since from what i read it does not seems to be needed for my case as my app do not have a registration function in the website or app.

I am assuming the linking of AutofillEffect.cs and the AppleAutofillEffect.cs is not link properly.

Code for AutofillEfect.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace MyProject
{
    public class AutofillEffect : RoutingEffect
    {
        public AutofillContentType Type { get; set; }

        public AutofillEffect() : base("PasswordAutofill." + nameof(AutofillEffect))
        {
        }
    }
}

Code for AppleAutofillEffect.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using Foundation;
using UIKit;

[assembly: Xamarin.Forms.ResolutionGroupName("PasswordAutofill")]
[assembly: Xamarin.Forms.ExportEffect(typeof(MyProject.iOS.AppleAutofillEffect), "AutofillEffect")]
namespace MyProject.iOS
{
    public class AppleAutofillEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var effect = (AutofillEffect)Element.Effects
                .FirstOrDefault(e => e is AutofillEffect);
            if (effect != null
                && UIDevice.CurrentDevice.CheckSystemVersion(11, 0)
                && Control is UITextField textField)
            {
                switch (effect.Type)
                {
                    case AutofillContentType.None:
                        textField.TextContentType = NSString.Empty;
                        break;
                    case AutofillContentType.Username:
                        textField.TextContentType = UITextContentType.Username;
                        break;
                    case AutofillContentType.Password:
                        textField.TextContentType = UITextContentType.Password;
                        break;
                }
            }
        }

        protected override void OnDetached()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)
                && Control is UITextField textField)
            {
                textField.TextContentType = NSString.Empty;
            }
        }
    }
}

Login.xaml

<StackLayout x:Name="loginForm">
         <Label Text="Username" TextColor="#0071BB" FontSize="16" FontFamily="Roboto" HorizontalTextAlignment="Center"></Label>                            
          <inputLayout:SfTextInputLayout OutlineCornerRadius="20" ContainerBackgroundColor="#000" >
                  <Entry x:Name="txtUsername" BackgroundColor="#FFF" TextColor="#FFF" FontSize="20" FontFamily="Roboto">
                           <Entry.Effects>
                                  <local1:AutofillEffect Type="Username" />
                           </Entry.Effects>
                     </Entry>
            </inputLayout:SfTextInputLayout>
           <Label Text="Password" TextColor="#0071BB" FontSize="16" FontFamily="Roboto" HorizontalTextAlignment="Center"></Label>
           <inputLayout:SfTextInputLayout OutlineCornerRadius="20"  ContainerBackgroundColor="#000">
                    <Entry x:Name="txtPassword" BackgroundColor="#FFF" TextColor="#FFF" FontSize="20" FontFamily="Roboto" IsPassword="True">
                            <Entry.Effects>
                                    <local1:AutofillEffect Type="Password" />
                            </Entry.Effects>
                     </Entry>
             </inputLayout:SfTextInputLayout>
            <buttons:SfButton Text="Login" CornerRadius="20" x:Name="btnLogin" Clicked="btnLogin_Clicked" FontFamily="Roboto-Light" FontSize="20" 
                                                          BackgroundColor="#0071BB" TextColor="#FFF" WidthRequest="150"/>
</StackLayout>

Directory Structure

  • MyProject.sln
    ---------- MyProject
    ----------------AutofillEffect .cs
    ----------------Views
    ---------------------Login.xaml
    -----------MyProject.iOS
    -----------------AppleAutofillEffect .cs

Android push notifications “Message was successfully sent, but there were no matching targets."

$
0
0

I am trying to setup push notifications on a Xamarin.Forms Android app following this tutorial and this sample. My AndroidManifest.xml, FirebaseService.cs and MainActivity.cs are basically the same as the sample. When I fire up the Android Emulator and do a Test Send from Azure Notification Hubs I get: "Message was successfully sent, but there were no matching targets." Is that tutorial outdated?


Printerest like CollectionView renderer for iOS in Xamarin.Forms?

$
0
0

After some research I could find the custom renderer for CollectionView in Android and it works great, but I couldn't find the equalant for iOS. Please help me create it for iOS. Thanks

Custom CollectionView for android:

[assembly: ExportRenderer(typeof(CollectionView), typeof(CustomCollectionViewRenderer))]
namespace App.Droid
{
    public class CustomCollectionViewRenderer : CollectionViewRenderer
    {
        public CustomCollectionViewRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<ItemsView> elementChangedEvent)
        {
            base.OnElementChanged(elementChangedEvent);

            if (elementChangedEvent.NewElement != null)
            {
                StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.Vertical);
                SetLayoutManager(manager);
            }
        }
    }
}

Custom CollectionView for iOS: ??

How can I add an item (just 1) from a list into another list?

$
0
0

Once I initialized two lists (a, b), I'd like to add one item from list "a" into "b" whenever I press a button. Note, JUST 1 and not the whole list. With my current code, my list "b" keeps being null.

This is what I've tried

//Initialize / declare lists

public List a;

    List<string> b= new List<string>();

// List a
a = new List()
{
new Question() { QuestionText="", Answer=false } ,
new Question() { QuestionText="", Answer=false },
new Question() { QuestionText="", Answer=true },
new Question() { QuestionText="", Answer=false },
new Question() { QuestionText="" , Answer=true },
new Question() { QuestionText="", Answer=false },
new Question() { QuestionText="", Answer=false },

        };

//Add method---this is what I tried for adding items
if (_currentAnswerValue == false)
score++;

            else
            {
                b.Add(QuestionText.ToString());

How to use multiple fonts in a single label or another control

$
0
0

Hi everyone,

I am retrieving data from sqlite database and there is a single field which contains two languages i.e. Urdu and Arabic. If I use urdu font then arabic text is not looking good and sometimes non-readable. And if I use arabic font then urdu text is not looking good. Is there any possibility that I could use separate fonts for different languages in a single field?

بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ
عظیم اور دائمی رحمتوں والے خدا کے نام سے

I can modify the data in database to have some tags in it like:

بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ
عظیم اور دائمی رحمتوں والے خدا کے نام سے

Any idea would be fantastic.

Thanks.

Is it possible to add android zoom buttons on only one webview?

$
0
0

I have one web view where I need the zoom buttons enabled, but they look tacky and get in the way of other web views.

I know how to set the zoom buttons up using this.Control.Settings.SetSupportZoom(false); ,
but it applies to every single web view.

In my CustomWebViewRenderer I have no way to reference what url I'm actually using to open the webview. Instead, the url just returns "file:///android_asset/"

Any ideas of how I co do something like...

if(url == "example.com")
this.Control.Settings.SetSupportZoom(true)
else
this.Control.Settings.SetSupportZoom(false)

It doesn't have to be exactly that, just the same effects.

Xamarin.Forms Fiddle (Code, Scan and Run)

$
0
0

With Web Atoms Playground, you can create Xamarin.Forms apps in JavaScript. You can write JSX instead of Xaml and that gives you powerful multibinding and allows you to push code on production.

  1. Side by side versioning
  2. Divide large app in multiple javascript npm packages
  3. No need to create multiple apps and integrate all of them
  4. Debug JavaScript in Chrome using V8 Inspector protocol for Android
  5. Debug JavaScript in Safari debugger for iOS

Download the App

App Store

Play Store

Open Demo

Shapes

https://www.webatoms.in/play/demo/shapes/1
https://www.webatoms.in/play/demo/rating/4

Explore new feature "Shapes" of Xamarin.Forms 4.7.

Master Detail

https://www.webatoms.in/play/demo/master-detail

Application with drawer and multiple pages, using navigation service to open pages, retrieve result and load unpacked pages.

List View

https://www.webatoms.in/play/demo/list

Explore list view with Cell bindings. Using two way binding to update the selection.

Form

https://www.webatoms.in/play/demo/form/3

Explore validation sample with simple form.

Tabbed Page

https://www.webatoms.in/play/demo/tabbed-page/3

Explore tabbed pages.

Scan QR Code

Scan and Play

Console Logging

You can see console of your device and you can log errors/warnings in the console in your code.

Setting Initial Value to Picker MVVM Xamarin Sets ObservableCollection to NULL

$
0
0

I'm trying to set the initalvalue of a picker in a a list view. However, when I have tried to do this through many methods, nothing is set and the underlying source (the property IngredientName for each element of downloadedRecipeIngredients) (the array is initially correct prior to being stored in teh ObserverableCollection) is set to null. This can be seen when utilizing breakpoints in the for loop which get data and stores it to DownloadedRecipeIngredients.

The picker is populated with a list of strings and the choices are displayed correctly when you click on the picker. This list is stored in _listIngredients. These are the possible ingredients one can utilize with a given recipe.

I'm trying to set the initial value to IngredientName which is also a string.

Please help. Thanks.

The picker in question is named 'pickerIngredientancestor'

XAML

<ContentPage.Content>
    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <ListView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" ItemsSource="{Binding downloadedRecipeIngredients}">  <!--SelectedItem="{Binding SelectedItem}"-->
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Picker x:Name="pickerIngredientancestor" HorizontalOptions = "StartAndExpand" ItemsSource="{Binding listIngredients, Source={RelativeSource AncestorType={x:Type viewModel:testPageViewModel}}}" SelectedItem="{Binding IngredientName}" WidthRequest="100"/>
                            <Entry Text="{Binding Comments}" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" />
                            <Label Text="Clickable Label" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand">
                                <Label.GestureRecognizers>
                                    <TapGestureRecognizer Command="{Binding Path=BindingContext.btnPress, Source={x:Reference Page}}" CommandParameter="{Binding .}" />
                                </Label.GestureRecognizers>
                            </Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

VIEW MODEL

public class testPageViewModel : BaseViewModel
{
    ObservableCollection<clRecipeIngredient> _downloadedRecipeIngredients = new ObservableCollection<clRecipeIngredient>();
    public ObservableCollection<clRecipeIngredient> downloadedRecipeIngredients
    { 
        get { return _downloadedRecipeIngredients; } 
        set 
        {
            _downloadedRecipeIngredients = value;
            OnPropertyChanged();
        } 
    }

    ObservableCollection<string> _listIngredients = new ObservableCollection<string>();
    public ObservableCollection<string> listIngredients { get { return _listIngredients; } }

    private clRecipeDataBase recipeDataBase;

    public testPageViewModel()
    {
        recipeDataBase = new clRecipeDataBase();

        getData();
    }

    async void getData()
    {
        //PICKER INGREDIENT DATA
        clIngredient[] tmp = await recipeDataBase.getIngredientData();
        //picker.ItemsSource = null;

        for (int i = 0; i < tmp.Length; i++)
        {
            _listIngredients.Add(tmp[i].IngredientName);
        }

        clRecipeIngredient[] arr = await recipeDataBase.getRecipeIngredientsDataByRecipeID(310); //HARDCODED TO CRISPY PIZZA RECIPE
        clRecipeIngredient tmp1;
        for (int i = 0; i < arr.Length; i++)
        {
            _downloadedRecipeIngredients.Add(arr[i]);
        }


    }

Trying to get the value of a picker's selectedItem within a listview (MVVM)

$
0
0

Need some direction/help here guys. Similar to a basic contacts app - I'm building a customer entry screen and need a drop down for contact types (phone, email, etc). I figured out how to populate the picker(s) by explicitly defining the path and source but I can't seem to get SelectedItem to do anything. My expectation is set the default value of the picker with whats in the record and also be able to change that value.

<ListView x:Name="ContactListView" ItemsSource="{Binding Customer.ContactList}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Picker
ItemsSource="{Binding Path=BindingContext.ContactTypes, Source={x:Reference ContactListView} }"
ItemDisplayBinding="{Binding TypeName}"
SelectedItem="{Binding TypeName, Mode=TwoWay}"
/>
<Entry Text="{Binding Value}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

The ViewModel attached to this page has an Customer object which has a nested contact list in it (defined at the list view). Each contact has a picker with multiple types and a value field so they can type in the corresponding data.


Custom List from other list

$
0
0

Hi friends, how are things going there?

I'm new in XF and I'm facing a issue that I'm not able to solve alone.

I need to create a custom List from other to use in picker.itemsource. When I use the original List it brings all columns (Name, Address, Phone etc.) from that list, but I need just the Names, do you know?

I want to use this value as parameters to a complex search screen (see attached image). I'm using just an entry field but I want to avoid the user commit some mistake while using the search, does it make sense?

Any help will be appreciated.

Thanks and best regards.

Navigation Confusion

$
0
0

I am obviously missing something or not understanding the Navigation correctly. I have a UserLogin page that when the user logs in they are sent to another page for two factor authentication.

await Navigation.PushModalAsync(new TwoFactorPage(UserKey, TicketValue));

this works fine and it the user get the two factor correct I send them onto the main page

await Navigation.PushModalAsync(new MainPage(UserKey));

But if the user gets the two factor incorrect I want to send them back to the userlogin page but everything I do results in a error.
I thought I was supposed to use

await Navigation.PopAsync();

but that doesn't work, give the me lovely "is not supported globally on Android, please use a NavigationPage"

So am I doing my page navigation wrong? How do I go back a page?

How to highlight newly added item to CollectionView

$
0
0

I am using Xamarin forms.I have CollectionView in Xamarins showing List of Tickets.I want to highlight new rows whenever its inserted.Like flashing or blinking the row with red background say for 5 seconds.After 5 seconds it should be normal row. Clients will add rows in real time using SignalR.


<CollectionView.ItemTemplate>

                        <Frame x:Name="frame1" BackgroundColor="White" BorderColor="#F0F0F0" Padding="3" Margin="0,0,0,5" HasShadow="False" CornerRadius="10" DescendantAdded="Frame_DescendantAdded">
                            <Grid HeightRequest="40" HorizontalOptions="FillAndExpand" VerticalOptions="Start">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="2*"/>
                                    <ColumnDefinition Width="2*" />
                                    <ColumnDefinition Width="6*" />
                                </Grid.ColumnDefinitions>

                            <Label Grid.Column="0" x:Name="lb_TicketNumber" Text="{Binding TicketNumber}" TextColor="Black" FontSize="Large" FontAttributes="Bold" VerticalOptions="Center" Margin="20,0" HorizontalTextAlignment="Center"  />
                            <Label Grid.Column="1" Text="{Binding DeskName}" TextColor="Black" FontSize="Large" FontAttributes="Bold" VerticalOptions="Center" HorizontalTextAlignment="Center"/>
                            <Label Grid.Column="2" Text="{Binding ServiceNameEng}" TextColor="Black" FontSize="Large" FontAttributes="Bold" VerticalOptions="Center" HorizontalTextAlignment="Center" />

                            </Grid>

                        </Frame>

                </DataTemplate>
            </CollectionView.ItemTemplate>

        </CollectionView>

Shell: Register routes when app starts (before you start AppShell

$
0
0

Hi there
in my main AppShell I register routes like this
[code]
public partial class MainPage : Xamarin.Forms.Shell
{
public MainPage()
{
InitializeComponent();
RegisterRoutes(); //Register page route so we can navigate to the page
}

    //Register page route so we can navigate to the page
    public void RegisterRoutes()
    {
        Routing.RegisterRoute("showImage", typeof(ShowImagePage));
    }
}

[/code]
if I first start the app so it goes to a home page I can navigate to here fine
my App.xaml.cs looks like this
[code]
public partial class App : Application
{
public App()
{
InitializeComponent();

        MainPage = new MainPage();
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }

    //Show image that user wants to share with our app
    public void ShowImage() //this method couses problems if I call this method direcly from native part b4 my app shows home page my app will crash
    {
        Task.Run(async () => await Shell.Current.GoToAsync("showImage")); //Go to the route we registered
    }

[/code]

but in my Native part I hook insto share dialog and want to show this showImage page when user shares a file
[code]
[Activity(Label = "clip2url", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = @image/jpeg)] //Declaration to handle incoming files via share dialog
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        global::Xamarin.Forms.Forms.SetFlags("Shell_Experimental", "Visual_Experimental", "CollectionView_Experimental", "FastRenderers_Experimental");
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        //Init Xmarin Plugins
        ImageCircle.Forms.Plugin.Droid.ImageCircleRenderer.Init(); //Init native Image library

        //To get acsess to Xamarin Forms part
        var mainForms = new App();
        LoadApplication(mainForms);

        //Here we tell out app what do we want to do with this share dialog data
        if (Intent.Action == Intent.ActionSend)
        {
            mainForms.ShowImage(); //here I call my ShowImage method and I want the page to be displayed but now my home page a seperate page and I want to then navigate back to home page
        }
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

[/code]

now if I start the app from home screen then try to share file it works fine, but if I start my app from share dialog, then my app crashes as routes for some reason don't get registered and I cannot navigate to my ShowImage page if I didn't first open my MainPage

Hope someone can shed some light to this and help me figure out whats is wrong :smile:

Thanks

error MT2091

$
0
0

I am getting this error when building for iOS Release with Linker set to all or sdk framework.
error MT2091: Inliner failed processingSystem.Void MacAttribute::.ctor(System.Byte,System.Byte)``

What does that mean? I cannot find much on that error.

Viewing all 91519 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>