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

StackLayout Content Binding

$
0
0

I'm really new to Xamarin and Xamarin forms and I need some help.

I have a StackLayout to which I want to add items dynamically from my ViewModel. Problem is I can't seem to bind the content of the StackLayout to my ViewModel's StackLayout.

this is my xaml code in my view

<StackLayout/>

I want something like

<StackLayout Content="{Binding MainStackLayout}"/>

I have a StackLayout already setup in my ViewModel like this

public StackLayout MainStackLayout;

Tab indicator in Xamarin Forms Tabbed Page placed at bottom

$
0
0

I have a Xamarin Forms bottom placed tabbed page rendered using C#. I want a tab indicator to be displayed above each tab icons as it would in a top placed tabbed page. Is it possible? I am not able to find solution anywhere. I came across this SO post - https://stackoverflow.com/a/41570159/10329199, where we can define app:tabIndicatorColor="#123456" in Tabbar.axml. But I didnt work because I'm rendering the tabbar using C# not in AXML. I also want this tab indicator in iOS. Thanks

Network issues in Xamarin forms httpclient

$
0
0

Our mobile app heavily depends on continuous syncing between app and server. For this we run multiple api's in the background(parallely) to fetch the data (like Account, Acc related items etc).

Every 5 mins sync process starts and it instantiates 12 api's. I have a backgroundtask(where I', handling httpclient methods) where all the 12 api's calls this task to fetch it's respective data.

public BackgroundTask(string authToken)
{
client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
}
api call:

private async TTask PostReturnMultipleAsync(string api, object postContent, CancellationToken cancellationToken)
{
try
{
var serializedContent = JsonConvert.SerializeObject(postContent);
HttpContent httpContent = new StringContent(serializedContent, Encoding.UTF8, "application/json");
response = await client.PostAsync(Constants.BaseUrl + "/" + api, httpContent, cancellationToken);
}catch(Exception ex){}
}
The issue is sometimes I'm getting strange errors in some sync process related to network. Let's say sync process starts at 12:00 pm I will be getting errors in some api's and another sync process starts at 12:10 pm, then it works fine.

The errors details are as follows:

[6/23/2020 8:16:26 AM] The network connection was lost.
at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x1035be040 + 0x009a3> in <75e8f2cafde249969958834208668188#2628be6571b6c601843a6a945b784ff0>:0 at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) <0x1034e1cd0 + 0x005f4> in <692b89da4aac4c12a3ac3af90678ac25#2628be6571b6c601843a6a945b784ff0>:0 at TCRMobile.Tasks.BackgroundTask1[T].PostAsync (System.String api, System.Object postContent, System.Threading.CancellationToken cancellationToken) <0x103971430 + 0x00377> in <570cf8f88c3948a1b77300eead58c259#2628be6571b6c601843a6a945b784ff0>:0

[6/23/2020 8:16:26 AM] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=53, NSUnderlyingError=0x280158510 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=53, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <1695E60D-6530-4BD8-A2B2-08E8E8C3C317>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <1695E60D-6530-4BD8-A2B2-08E8E8C3C317>.<1>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://apps.tcrsoftware.com/tcrservices/api/Tickets/GetTickets

[6/22/2020 1:43:13 PM] A task was canceled.
at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x101d92040 + 0x009a3> in <75e8f2cafde249969958834208668188#2628be6571b6c601843a6a945b784ff0>:0 at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean

I tried setting timeout to 50 seconds, that doesn't helps too. Any better to do this?

How to the CSS for each platform in the App.xaml?

$
0
0

I've tried and tried but can't get this to work. Maybe it's not possible. I would like to load a css file per platform. Here's what I've tried.

<?xml version="1.0" encoding="utf-8" ?>
<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="eTabber.App">
    <Application.Resources>
        <StyleSheet Source="/css/Main.css" />
        <StyleSheet Source="{OnPlatform iOS=/css/iOS.css, Android=/css/Android.css}" />
    </Application.Resources>
</Application>

ERROR: Source is not a String Literal

and this:

<?xml version="1.0" encoding="utf-8" ?>
<Application
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="eTabber.App">
    <Application.Resources>
        <StyleSheet Source="/css/Main.css" />
        <StyleSheet Source="/css/Dummy.css" >
            <StyleSheetExtension.Source>
                <OnPlatform x:TypeArguments="x:Uri">
                    <On Platform="Android">/css/Android.css</On>
                    <On Platform="iOS">/css/iOS.css</On>
                </OnPlatform>
            </StyleSheetExtension.Source>
        </StyleSheet>
    </Application.Resources>
</Application>

This compiles but does nothing at all (Ok, it does load the dummy.css). If I leave out the 'Dummy.css' it complains it needs a 'Source'.

I also tried loading it in code behind. That works but then 'Hot XAML reloading' is not working.

B.t.w: compilation of this stuff is just instable. I had to delete 'bin' and 'obj' on several occasions and also had to restart VS2019.

How to connect to localhost NetCore 3.1 rest api from within iOS and Android project?

$
0
0

I am using MVVM Prism for the Xamarin mobile app.

I created a NetCore 3.1 rest api that serves as the backend to my Xamarin mobile app. I want to be able to debug it locally.
I would like to:

A. Connect to localhost to debug the rest api from the Simulators
B. Also would like to connect to the localhost kestrel from the mobile app itself in debug mode if possible

I am using NetCore Kestrel instead of IIS to host the rest api in the localhost.

I can connect with Postman locally and DEBUG ok in VS using this URL:

even though I do get a first certificate validation error, but I turned off Certificate validation in POSTMAN to make it work, but when I try to connect to that same URL from the mobile, with the code below I get this error:

I have been struggling with this for 2 full days, this is my code:

REST API PROJECT

Program.cs class:

namespace MyAppNamespace
{
    public class Program
    {

        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                 .ConfigureServices((context, services) =>
                 {
                     services.Configure<KestrelServerOptions>(
                         context.Configuration.GetSection("Kestrel"));
                 })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        // Set properties and call methods on options
                        serverOptions.Limits.MaxConcurrentConnections = 100;
                        serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
                        serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
                        serverOptions.Limits.MinRequestBodyDataRate =
                            new MinDataRate(bytesPerSecond: 100,
                                gracePeriod: TimeSpan.FromSeconds(10));
                        serverOptions.Limits.MinResponseDataRate =
                            new MinDataRate(bytesPerSecond: 100,
                                gracePeriod: TimeSpan.FromSeconds(10));
                        serverOptions.Listen(IPAddress.Loopback, 5000);
                        serverOptions.Listen(IPAddress.Loopback, 5001,
                            listenOptions =>
                            {
                                listenOptions.UseHttps(",myapphosting.pfx",
                                    "mypassword");                                                 // I did not specify where these files are in the code, it seems to just know?
                            });
                        serverOptions.Limits.KeepAliveTimeout =
                            TimeSpan.FromMinutes(2);
                        serverOptions.Limits.RequestHeadersTimeout =
                            TimeSpan.FromMinutes(1);                 
                    })         
                    .UseStartup<Startup>();
                });
     }
}

Startup class:

namespace MyAppNamespace
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc(option => option.EnableEndpointRouting = false)
           .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
           .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(options =>
               {
                   options.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateIssuer = true,
                       ValidateAudience = true,
                       ValidateLifetime = true,
                       ValidateIssuerSigningKey = true,
                       ValidIssuer = Configuration["Tokens:Issuer"],
                       ValidAudience = Configuration["Tokens:Issuer"],
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                       ClockSkew = TimeSpan.Zero,
                   };
               });
            services.AddDbContext<MyAppDbContext>(option => option.UseSqlServer("MyConnectionString"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyDbContext myDbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //else
            //{
            //    app.UseHsts();
            //}

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            myDbContext.Database.EnsureCreated();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

launchSettings.Json :

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iis": {
      "applicationUrl": "http://localhost/MyWebApiName",
      "sslPort": 0
    },
    "iisExpress": {
      "applicationUrl": "http://localhost:52080",
      "sslPort": 44349
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/accounts/register",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "YWAW.WebApi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/accounts/register",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    }
  }
}

I followed this tutorial to set up the to bypass the Bypass the certificate security check and grab an insecurehandler on both Android and iOS platforms.
https://docs.microsoft.com/en-us/xamarin/cross-platform/deploy-test/connect-to-local-web-services

XAMARIN FORMS PROJECT

in Constants class(shared project):

public static string BaseAddress =
    Device.RuntimePlatform == Device.Android ? "https://10.0.2.2:5001" : "https://localhost:5001";  // here I tried writing the iOS url as in Postman above too, same result
public static string RestUrl = $"{BaseAddress}/api/Accounts/Register";

App.Xaml.cs

public partial class App
    {
        /* 
         * The Xamarin Forms XAML Previewer in Visual Studio uses System.Activator.CreateInstance.
         * This imposes a limitation in which the App class must have a default constructor. 
         * App(IPlatformInitializer initializer = null) cannot be handled by the Activator.
         */
        public App() : this(null) { }

        public App(IPlatformInitializer initializer) : base(initializer) { }

        protected override async void OnInitialized()
        {
            InitializeComponent();

            await NavigationService.NavigateAsync("NavigationPage/HomePage");
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<IAppInfo, AppInfoImplementation>();

            containerRegistry.RegisterForNavigation<NavigationPage>();

            containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
            containerRegistry.RegisterForNavigation<HomePage, HomePageViewModel>();
            containerRegistry.RegisterForNavigation<LoginPage, LoginPageViewModel>();
            containerRegistry.RegisterForNavigation<SignUpPage, SignUpPageViewModel>();
            containerRegistry.RegisterForNavigation<DefaultCustomActivityIndicatorPage, DefaultCustomActivityIndicatorPageViewModel>();
            containerRegistry.RegisterForNavigation<DiscoverDealsTabbedPage, DiscoverDealsTabbedPageViewModel>();

            containerRegistry.Register<ApiServices>(); //not sure if I actually should register this too
        }

        // add for app center analytics and crashes
        protected override void OnStart()
        {
            base.OnStart();

            AppCenter.Start("ios=secretkey" +
                  "uwp={Your UWP App secret here};" +
                  "android={Your Android App secret here}",
                  typeof(Analytics), typeof(Crashes));
        }
    }

LoginPageViewModel.cs

public class LoginPageViewModel : BindableBase
    {
        private IPageDialogService _dialogService { get; }
        private ApiServices _apiService { get; }

        public DelegateCommand SignInWithEmailTappedCmd { get; set; }

        public DelegateCommand SignInWithFacebookTappedCmd { get; set; }

        public DelegateCommand SignInWithGoogleTappedCmd { get; set; }

        private IFacebookClient _facebookService = CrossFacebookClient.Current;
        private IGoogleClientManager _googleService = CrossGoogleClient.Current;

        public INavigationService NavigationService { get; set; }
        private readonly ICustomActivityIndicatorPage _customActivityIndicator;

        private string _emailAddress;

        public string EmailAddress
        {
            get => _emailAddress;
            set => SetProperty(ref _emailAddress, value);
        }

        private string _password;

        public string Password
        {
            get => _password;
            set => SetProperty(ref _password, value);
        }

        public LoginPageViewModel(ICustomActivityIndicatorPage customActivityIndicator,
                                  IHttpClientHandlerService httpClientHandlerService,
                                  INavigationService navigationService,
                                  IPageDialogService dialogService)
        {
            _customActivityIndicator = customActivityIndicator;
            SignInWithEmailTappedCmd = new DelegateCommand(SignInWithEmailTapped);
            SignInWithFacebookTappedCmd = new DelegateCommand(async() => await SignInWithFacebookTapped());
            SignInWithGoogleTappedCmd = new DelegateCommand(async() => await SingInWithGoogleTapped());
            NavigationService = navigationService;
            _dialogService = dialogService;
            _apiService = new ApiServices(httpClientHandlerService);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private async Task SignInWithFacebookTapped()
        {
            try
            {
                if (_facebookService.IsLoggedIn)
                    _facebookService.Logout();

                EventHandler<FBEventArgs<string>> userDataDelegate = null;

                _customActivityIndicator.InitActivityPage(new DefaultCustomActivityIndicatorPage());
                _customActivityIndicator.ShowActivityPage();

                userDataDelegate = async (object sender, FBEventArgs<string> e) =>
                {
                    switch (e.Status)
                    {
                        case FacebookActionStatus.Completed:
                            var facebookProfile = await Task.Run(() => JsonConvert.DeserializeObject<FacebookProfile>(e.Data));

                            // save the user to the db if doesn't exist
                            UserToRegister user = new UserToRegister
                            {
                                Email = facebookProfile.Email,
                                FirstName = facebookProfile.FirstName,
                                LastName = facebookProfile.LastName
                            };

                            // THIS IS WHERE I TRY TO ACCESS THE LOCALHOST REST API
                            **var registerOutcome = await _apiService.Register(user);**

                            await NavigationService.NavigateAsync("DiscoverDealsTabbedPage");
                            _customActivityIndicator.HideActivityPage();
                            break;
                        case FacebookActionStatus.Canceled:
                            _customActivityIndicator.HideActivityPage();
                            await _dialogService.DisplayAlertAsync("Facebook Auth", "Canceled", "Ok");
                            break;
                        case FacebookActionStatus.Error:
                            _customActivityIndicator.HideActivityPage();
                            await _dialogService.DisplayAlertAsync("Facebook Auth", "Error", "Ok");
                            break;
                        case FacebookActionStatus.Unauthorized:
                            _customActivityIndicator.HideActivityPage();
                            await _dialogService.DisplayAlertAsync("Facebook Auth", "Unauthorized", "Ok");
                            break;
                    }

                    _facebookService.OnUserData -= userDataDelegate;
                };

                _facebookService.OnUserData += userDataDelegate;

                string[] fbRequestFields = { "email", "first_name", "picture", "gender", "last_name" };
                string[] fbPermisions = { "email" };
                await _facebookService.RequestUserDataAsync(fbRequestFields, fbPermisions);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                _customActivityIndicator.HideActivityPage();
            }
        }

    }

ApiServices class:

public class ApiServices
    {
        private HttpClient httpClient;
        private string apiRegisterURL;
        private readonly IHttpClientHandlerService _httpClientHandler;

        public ApiServices(IHttpClientHandlerService httpClientHandler)
        {
#if DEBUG
            _httpClientHandler = httpClientHandler;
            httpClient = new HttpClient(_httpClientHandler.GetInsecureHandler());
            apiRegisterURL = Constants.RestUrl;
#else
            httpClient = new HttpClient();
            apiRegisterURL = Constants.REGISTER_URL;
#endif    
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<RegisterOutcome> Register(UserToRegister user)
        {
            RegisterOutcome outcome = new RegisterOutcome();

            //var httpClient = new HttpClient();

            try
            {
                var json = JsonConvert.SerializeObject(user);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                outcome.ResponseMessage = await httpClient.PostAsync(apiRegisterURL, content);
            }
            catch (Exception ex)               // ERROR IS HERE CONNECTION REFUSED
            {
                outcome.ErrorMessage = ex.Message;
            }

            return outcome;
        }
    }

IOS PROJECT:

iOSHttpClientHandlerService.cs:

[assembly: Dependency(typeof(iOSHttpClientHandlerService))]
namespace YWAWMobileApp.iOS.Services
{
    public class iOSHttpClientHandlerService : IHttpClientHandlerService
    {
        public HttpClientHandler GetInsecureHandler()
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
            {
                if (cert.Issuer.Equals("CN=localhost"))
                    return true;
                return errors == System.Net.Security.SslPolicyErrors.None;
            };
            return handler;
        }
    }
}

AppDelegate.cs:

public class iOSInitializer : IPlatformInitializer
    {
        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // Register any platform specific implementations
            containerRegistry.Register<ICustomActivityIndicatorPage, iOSCustomActivityIndicatorPage>();
            containerRegistry.Register<IHttpClientHandlerService, iOSHttpClientHandlerService>();
        }
    }

ANDROID project same as IOS.

How to dismiss multiple pages using PopModalAsync?

$
0
0

I need to close 2 pages and show my home page after an operation. I try to do it with MessagingCenter, but sometimes it redirects me to the login page.

So is it possible to do this with multiple PopModalAsync?

Thanks in advance :)

How to get NavigationBar height?

$
0
0
I want to get NavigationBar height because i want to place center of the app.
If i get NavigationBar height then i can use margin to place center but i did not find way to get NavigationBar height.

Play Media file from Resource

$
0
0

Hi,

I have an MP3 file in my Android's Resources/Raw folder, the file name is myAudio.mp3

The same file is placed in my iOS Resources/myAudio.mp3

I am trying to play the file uaing Xamarin Mediamanager plugin but it's not playiing any sound

I tried this:

await CrossMediaManager.Current.Play("raw/myAudio.mp3");

and this:

await CrossMediaManager.Current.PlayFromResources("raw/myAudio.mp3");


Google map screenshot always black screen

$
0
0

I want to take google map screenshot in my xamarin PCL Project. The map is displaying perfectly. But when i try to take a screenshot it is displaying a black screen for the map part. But extra part of the screen is capture perfectly. When i try to take screenshot from another app, i can take perfectly. I am using the below code.

My interface

public interface IScreenshotService { Task<byte[]> Capture(); }
`
public class ScreenshotService : IScreenshotService
{
public static Activity Activity { get; set; }

public async System.Threading.Tasks.Task<byte[]> Capture()
{
    if (Activity == null)
    {
        throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
    }

    var view = Activity.Window.DecorView;
    view.DrawingCacheEnabled = true;

    Bitmap bitmap = view.GetDrawingCache(true);

    byte[] bitmapData;

    using (var stream = new MemoryStream())
    {
        bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
        bitmapData = stream.ToArray();
    }

    return bitmapData;
}

}

`

Code to for calling function

byte[] screenshotData = await DependencyService.Get<IScreenshotService>().Capture();

Azure Notification Hubs with xamarin forms ios 13.5 or later ??????

$
0
0

Azure Notification Hubs still doesn't work with xamarin forms 13.5 or later?

Test on iSO without a MAC computer

$
0
0

It is possible that this question does not correspond to ask it but I would like to ask you if there is any alternative way to test the controls on iOS without having a MAC computer

It would help me a lot

How to get uri in shared project from platform specific event?

$
0
0

I need to get the uri in shared project(App.cs) from these platform events

in android
protected override async void OnNewIntent(Intent intent) { base.OnNewIntent(intent); //(i need this intent.DataString) }

in ios
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation) { //(i need this url.AbsoluteString) }

How to control playback speed of MediaElement in xamarin form?

$
0
0

Is there a way to control playback speed of MediaElement in xamarin form?

Can i code for a Xamarin.forms css style sheet base on platform? Can i target a style sheet?

$
0
0
  1. Is it possible to target an entire stylesheet base on platform for CSS?
  2. Is it possible to targe a specific style for a specific platform based on CSS?

How to measure a ContentView based on its content ?

$
0
0

Hi All,

I am having a ContentView where i add DataTemplate as its content. Is there any way to measure the size of the content view based on its content. Please note that its content can be any view. I can measure the size of the content if the height and width are explicitly set when defining the DataTemplate like in the below case.

<DataTemplate> <Entry x:Name="numeric" Text="{Binding FirstName}" FontSize="12" TextColor="Black" WidthRequest=150 HeightRequest=100 Keyboard="Numeric" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" /> </DataTemplate>

But when the height and width are not specified , the measure call returns -1 as width and height which is the behavior of the framework, since the measure call fetches the size only from the WidthRequest and HeightRequest properties. Is there any way to overcome this and get the actual size of the view based on the content.

Awaiting your suggestions. Thanks in advance !

Vimal Prabhu


I need help with Admod Native ad sample

$
0
0

I need help with Admod Native ad sample. Anyone have complete sample code with Admod Native ad can help me?
Thanks.

Navigation back to current carousel from LockScreen

$
0
0

i have a carousel page and on each of them i have a button and the user is able to lock the page. For that i am using dependency service and that works fine, however if i want to come back from the second page i am redirected to the first page and the page sort of "freezes". I need to be able to return to the second page of the carousel page. Can you help please?

I have tried INavigation but i am getting a null exception. 2.I have also tried just override OnBackButton but that gets me back to the main page 3. i have tried to save the page index but i am not sure how to proceed then

namespace AVAT.Droid.Renderers {

[Activity(Label = "LockScreenActivity", Theme = "@style/Theme.Splash")]
public class LockScreenActivity : FormsAppCompatActivity
{
INavigation _navigation;
public LockScreenActivity(INavigation navigation;)
{
learningPage = new LearningPage();
_navigation = navigation;

 }
 protected override void OnCreate(Bundle savedInstanceState)
 {
     base.OnCreate(savedInstanceState);


     // Set our view from the "main" layout resource
     SetContentView(Resource.Drawable.lockScreenLayout);

     var button = FindViewById<Android.Widget.Button>(Resource.Id.backButton);
     button.Text = "JÍT ZPĚT";
     var index = learningPage.beforeLock;
     button.Click += delegate
     {
         FinishAndRemoveTask();
        // _navigation.PopAsync();
     };
 }



 public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
 {
     if (keyCode == Keycode.VolumeDown)
     {
         Player.GoOneSentenceBack(Article.GetTrackId());
         return true;
     }

     if (keyCode == Keycode.VolumeUp)
     {
        PlayPause();
         return true;
     }
     else
     {
         return base.OnKeyDown(keyCode, e);
     }

 }

}

please help

Slider Behavior in ScrollView

$
0
0

I have a fairly complicated hierarchy of controls, going from a ScrollView to a ListView, to a StackLayout with a combination of buttons and a slider. If a user scrolls the page, they can start the swipe from most anywhere, including on top of a button, and the page will scroll without triggering any UI control events. However, if they try to scroll and accidentally start swiping up or down from on top of a slider, the slider moves instead of the page scrolling.

Is there any reason this is different from the way the buttons work? Is it possible to wait until the gesture is confirmed to be horizontal before allowing the slider to activate? It's frustrating to users when they are just trying to scroll through the page but accidentally change a slider value. I can change the workflow a bit to require confirmation of a slider change, or unlock the slider first somehow, but it'd be nice to keep things simple like they are.

How to implement WKWebview in xamarin.forms ?

$
0
0

Hello,

I want to pass one url in my webview. But as IOS appstore gives error so I want to implement WKWebview but I want to know how can implement it? Please help me out its urgent.

Xamarin Forms iOS app is running perfectly on an emulator but crashing after splash screen on iPhone

$
0
0

Hi,

My Xamarin Forms iOS app is running perfectly on an emulator but crashing after splash screen on an iPhone device. I tried all the accepted from Xamarin Forums and StackOverflow. Nothing seems working.

I put try-catch blocks on Main.cs, AppDelegate.cs under the Xamarin Forms iOS app and under App.xaml.cs in the Xamarin Forms, it is not even triggering my try-catch blocks, even before the app crashes.

This occurs only on the real device [iPhone 6s iOS 13.3]

Viewing all 79144 articles
Browse latest View live