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

iPhone X SafeArea with Forms ListView

$
0
0

How do you guys handle the safe area problem for ListViews with Xamarin.Forms? Just setting the safe area as margin on the whole ListView looks ugly AF. So I search for something like a custom renderer to make the ListView as equal als possible to the UITableView in the iPhone X. My current solution bringt the ViewCells in the correct position but the Seperator is going off screen and the ShortGroup index is behind the Notch in some rotations. Beside from that, my current solution is way to much work to implement it in every project (because I use a CustomViewCell class as Workaround).

So how to implement a custom renderer for this problem? All of my current implementations seems not to work properly. And I guess waiting for Xamarin to fix this is not an option (because MasterDetail pages still not work on iOS SplitView and this was reported back in 2015 and is just ignored by Xamarin...).

Edit: The problem with the ListView in Xamarin.Forms did only occur if the ListView control is not the root of the ContentPage. In my case it is inside a Grid because I want a SearchBar too on this side. In this case the content of the ListView (and the ShortGroup index) gets cut off by the iPhone X rounded corners and the notch. It looks really ugly and I guess it is a very common way to have a SearchBar and a ListView on one side. Here is a repository of a project which has a first workaround (the ShortGroup index still has the problem there and also the separator runs outside of the visible area while it normally would stop before that): https://github.com/Sebastian1989101/OpenGeoDB-App


General Android File System Confusion - Disappearing files

$
0
0

First, i would like to state I have been these threads:

Here: https://forums.xamarin.com/discussion/comment/13869#Comment_13869
Here: https://forums.xamarin.com/discussion/4878/database-sqlite-net-do-not-persist-between-build-on-monodroid
and
Here: https://forums.xamarin.com/discussion/6990/how-to-correctly-save-and-read-files

I have a section of code which checks for the existence of a .db file in this way:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string dbPath = Path.Combine(path, filename);

            if (!CheckdbVersion(dbPath, dbVersion))
            {
                DeleteFileIfExists(dbPath);
            }
            CopyDatabaseIfNotExists(dbPath);



 private static void CopyDatabaseIfNotExists(string dbPath)
        {
            if (!File.Exists(dbPath))
            {
                using (var br = new BinaryReader(Application.Context.Assets.Open("TSRDB.db")))
                {
                    using (var bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
                    {
                        byte[] buffer = new byte[2048];
                        int length = 0;
                        while ((length = br.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            bw.Write(buffer, 0, length);
                        }
                    }
                }
            }
        }

This works perfectly when debugging against an actual Android device (Samsung s5) in this case. I can close, stop, restart, minimize the app etc. and the file is only copied if it hasn't been copied previously or if the dbVersion doesn't match (ignore that piece, it's immaterial to my question). At least, I assumed that's what was happening. But, upon closer inspection of the device, the file never seems to be created on the card or the device storage.

I noticed this after my alpha testers started reporting issues and I discovered this method of doing a file stream to: Environment.SpecialFolder.Personal, does not seem to actually copy a file at all. Which is odd, since I'm also doing a File.Exists(dbPath) later and it comes back as true - exists during debug. In fact, everything seems to work perfectly until the app is installed from the play store, though I'm a little baffled as to why it ever works. The value of dbPath variable ends up being this: /data/user/0/com.myappid/files/TSRDB.db

No folder com.myappid is EVER created. At least, I cannot seem to find it when searching the entire device both external and internal storage at any point in time. What am I missing here?

Layout compression slowing down pages

$
0
0

Hello Folks,
today i tried the new layout compression feature, the results are quite disappointing.

In my last project, i have some complex view (lots of labels, stacklayout, grids, ecc...). They are working fine in IOS but i wanted to see if i can get more improvements. So i decided to add the magic CompressedLayout.IsHeadless=”true” to every layout without gestures, backgrounds etc...

Long story short: Now the pages are appearing waaay slower than before.

Before the change, when i navigated to a page, the content was immediately visible on screen. After enabling CompressedLayout, when i navigate to a page i see the background for like 2-3 seconds, then the content became visible.
The difference is very noticeable whitout measuring things in code or using inspectors.

Anyone noticed something similar? Its seem very odds to me... Any suggestion?

If you guys wants to try out this feature, use complex views, with lots of layouts to compress.

For now i switched back to my normal development without using CompressedLayout, maybe in future i'll do more tests.

Migrating to GitHub Issues and Projects

$
0
0

GitHub Issues

We're excited to announce GitHub Issues is now open on our repository. This is our new home for reporting bugs as well as discussing enhancement requests.

What does this mean?

  • Bugzilla will remain open for the time being, and existing issues will continue to be worked there
  • All new issues should be filed on GitHub
  • The Evolution forum is being deprecated. Existing proposals will remain. New proposals and requests should be moved to GitHub Issues

GitHub Projects

GitHub Projects has also recently been made available to us and we are discussing how we will use it for tracking issues, features, and other work. Watch that space for an even higher level of visibility into everything going on with Xamarin.Forms.

Xamarin UWP and Google Analytics

$
0
0

I am looking how to implement Google Analytics with Xamarin.UWP project specifically. After spending some time researching I find that Google Analytics now requires you to use Firebase, but Firebase supports only Android, iOS, and Web but not UWP.

I have found two Nugget packages that seem to support this:

  1. UWP.SDKforGoogleAnalytics

  2. ksemenenko.GoogleAnalytics

Has anyone implemented these with Xamarin.UWP projects successfully? Which one would you recommend?

How to change the IsVisible for the ContentPage at runtime?

$
0
0

Hi,

I am setting the IsVisible="false" for the ContentPage in my XAML.

I want to know how can I change it to true at runtime?

Here is my XAML:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="Eithar.Home" IsVisible="false"
    .................
    .................
    .................
    .................

Thanks,
Jassim

Help! This is Hell! Is the Xamarin Team listening?

$
0
0

I have an Android app I developed about a year ago on Xamarin Forms in VS2015. I checked it out to make some minor modifications, but I had reloaded Windows 10 since then. I fired up a completely fresh Windows 10 installation, installed VS2015 and ran Windows Update. I loaded the App code base and updated the NuGet packages (these are all Xamarin. ... packages, nothing unusual or third-party). I loaded the Oreo API in API Manager and took all the updates offered. When I rebuilt the code base, it completed without errors, but there were a couple of worrying messages:

Multiple instances of CS0618: Forms.Context is obsolete ...

"No way to resolve conflict between "mscorlib, Version=4.0.0.0, ... and "mscorlib, Version=2.0.5.0 ... Choosing mscorlib, Version=4.0.0.0 ... arbitrarily."

The last is in output only, neither an error or warning, but it sounds really bad, and choosing code arbitrarily is rarely the right thing to do in software!

Since there were no actual errors I went ahead to debug on a real ADB target (A Lenovo Tablet, Android 6.0 - API 23). The app loads up and presents an empty screen and then terminates on an exception before executing any of my code:

Java.Lang.RuntimeException: Unable to instantiate activity ComponentInfo ... Didn't find class "md59dfe07309ceba9bfe71a67493c5725be.MainActivity" on path: DexPathList[[zip file ...

I have no idea how to proceed and have tried everything I can think of including deleting everything Xamarin, Mono and App related from the tablet, deleting the bin and obj directories and re-building, reverting the code base and trying both before and after updating NuGet packages. None of this made any difference, though in the course of all this faffing about the app did successfully run on one occasion which I could not repeat.

Please, I am getting desperate, does anyone have any kind of handle on this or any suggestion as to how I can proceed?

Troubles with localization in XAML using MarkupExtension

$
0
0

Hello community,

I have a problem with non working localization in my Xamarin application.
I took the guide developer.xamarin.com/guides/xamarin-forms/advanced/localization/ as template and implemented it like described there.
Unfortunately the TranslateExtension does not work in my MainPage.xaml
I import the namespace as needed (only partial shown):
xmlns:resources="clr-namespace:mealticker.Resources"
That's the way I bind the text to the Label:
Label Text="{Binding resources:Translate Username}"
When running the program, nothing is shown in the Label.
The long version described in the article is not compilable:
Label Text="{Binding resources:TranslateExtension Text=Username}"
Compilers output: No property, bindable property, or event found for 'resources:TranslateExtension Text', or mismatching type between value and property.
The RESX stuff itself is working properly because when using the resource in code, the right text is shown.
Label Text="{Binding PasswordLabel}"
I also experiencing a warning in the output during compilation which I can't resolve:
0xdef00522 - Resources found for language(s) 'de,en' but no resources found for default language(s): ''. Change the default language or qualify resources with the default language.

Please have a look to the sourcecode located here: github.com/markus-fischbacher/quantumverde.git

Any help is appreciated.

Regards,
Markus


Issue with Samsung Note 8 running Android 7.1

$
0
0

My app invokes Call Phone intent. There is no problem with Marshmallow phones previously. But now on Note 8 I tried it for the first time. When I invoke the Call Phone intent I get the following Exception.Message.

Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxx cmp=com.android.server.telecom/.components.UserCallActivity launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } } from ProcessRecord{7dc990c 19695:Dates2Remember_XFAXU.Droid/u0a327} (pid=19695, uid=10327) with revoked permission android.permission.CALL_PHONE

A snip of my app's project properties is attached which shows that the Target version is set to 7.1 and the CALL_PHONE requirement is checked.

I am using dependency service. The dependant Android code is shown below. The following may be noted in this regard:

  1. Though Forms.Context is obsolete, it still works. However I have tried the other ways to set the Context also tried. The relevant code is commented below the Forms.Context usage.
  2. The error occurs at context.StartActivity(intent).

    using Android.Content;
    using Android.Telephony;
    using System;
    using System.Linq;
    using Xamarin.Forms;
    using Uri = Android.Net.Uri;

    [assembly: Dependency(typeof(PhoneDialer.Droid.PhoneDialer))]

    // For this to work ensure .Droid's Project Options -> Build
    // -> Android Application -> Required Permissions -> CallPhone
    // is checked.
    namespace PhoneDialer.Droid
    {
    public class PhoneDialer : IDialer
    {
    //Context context => Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity;

        // Dial the phone
        public bool DialFromDevice(string number, string displayName)
        {
            bool rtn_value = false;
    
            try
            {
                var context = Forms.Context;
                //Context context = Android.App.Application.Context;
                //var context = MyApp.Droid.MainActivity.instance;
    
                if (context != null)
                {
                    var intent = new Intent(Intent.ActionCall);
                    intent.SetData(Uri.Parse("tel:" + number));
    
                    if (IsIntentAvailable(context, intent))
                    {
                        context.StartActivity(intent);
                        rtn_value = true;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error: {0}", ex.Message);
                rtn_value = false;
            }
    
            return rtn_value;
        }
    
        // Checks if an intent can be handled.
        public static bool IsIntentAvailable(Context context, Intent intent)
        {
            var packageManager = context.PackageManager;
    
            var list = packageManager.QueryIntentServices(intent, 0)
                .Union(packageManager.QueryIntentActivities(intent, 0));
            if (list.Any())
                return true;
    
            TelephonyManager mgr = TelephonyManager.FromContext(context);
            return mgr.PhoneType != PhoneType.None;
        }
    }
    

    }

No issue with even Marshmallow simulator for VS. My Note 8 is still at API 25. It appears the project context is not passed on properly. Am I doing anything wrong?

Note: Unfortunately here if you employ multiple modes of formatting something will not presented correctly as required. Any suggestions to correct it, form myside, are welcome.

Detecting an element is currently within visual rendering space

$
0
0

With Xamarin Forms, is there a method for detecting if an element is currently within the visible portions of a screen?
What I am trying to achieve is the ability to detect when a user for example has scrolled on a page and if a video exists I can either stop playing it or unload it for performance reasons.

Get screen coordinates from Element for both Android and iOS?

$
0
0

I am trying to write a tutorial overlay, otherwise known as ShowcaseView or Coach Markups or Instructional overlay, component. I can handle the custom renderers and putting overlays on top of both Android and iOS screens. My problem though is knowing where the Elements are in screen coordinates specific to each platform to actually highlight the element. To make coding from the shared code side easy, I wanted to just specify the XF element as input to the tutorial overlay and make the tutorial overlay figure out what that Element's screen coordinates are. That is where I am stuck. Is there a nice way of taking an Element and getting the platform specific screen coordinates?

I tried using AutomationId and then scanning the UI hierarchy looking for that AutomationId (AccessibilityIdentifier in iOS), but it doesn't always work. For example, ToolBarItems do not support AutomationId (on Android at least) so I couldn't use it.

Any suggestions?

Change the localization of menu items in MasterDetailPage

$
0
0

Hello! I just can not understand what the problem is. Standard application with MasterDetailPage. I need the main menu items to change the text when the localization changes. The very change in the localization of text on the pages I did as described here, it works great.

MainPage.xaml looks like this:

<MasterDetailPage.Master>

    <ContentPage Title="Menu" BackgroundColor="#e8e8e8">

        <StackLayout Orientation="Vertical">

            <!--
         This StackLayout you can use for other
         data that you want to have in your menu drawer
    -->
            <StackLayout BackgroundColor="#e74c3c" HeightRequest="75">

                <Label Text="Main Menu"
                 FontSize="20"
                 VerticalOptions="CenterAndExpand"
                 TextColor="White"
                 HorizontalOptions="Center"/>
            </StackLayout>

            <ListView x:Name="navigationDrawerList"
              RowHeight="60"
              SeparatorVisibility="None"
              BackgroundColor="#e8e8e8"
              ItemSelected="OnMenuItemSelected"
              ItemTapped="OnMenuItemTapped"
              CachingStrategy = "RecycleElement"
             >
                <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <!-- Main design for our menu items -->
                        <StackLayout VerticalOptions="FillAndExpand"
                        Orientation="Horizontal"
                        Padding="20,10,0,10"
                        Spacing="20">
                            <Image Source="{Binding Icon}"
                            WidthRequest="40"
                            HeightRequest="40"
                            VerticalOptions="Center" />
                            <Label Text="{Binding Title}"
                            FontSize="Default"
                            VerticalOptions="Center"
                            TextColor="Black"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage>
</MasterDetailPage.Master>

MainPage.xaml.sc:

public partial class MainPage : MasterDetailPage
{

    public ObservableRangeCollection<MasterPageItem> MenuList { get; set; }
    MyViewModel vModel = null;
    MasterPageItem gamePageItem = null;
    Binding gpBinding = null;

    public MainPage(MyViewModel viewModel)
    {
        InitializeComponent();

        vModel = viewModel;

        gamePageItem = new MasterPageItem() { Title = vModel.Resources["LearningMenuItemText"], Icon = "learning.png", TargetType = typeof(GamePage) };
        gpBinding = new Binding(path: "Resources[LearningMenuItemText]", source: vModel);
        gamePageItem.SetBinding(MasterPageItem.TitleProperty, gpBinding);
// Adding menu items to menuList
        MenuList = new ObservableRangeCollection<MasterPageItem>()
        {
            gamePageItem
        };

        // Setting our list to be ItemSource for ListView in MainPage.xaml
        navigationDrawerList.ItemsSource = MenuList;

This works, but ONLY ONCE, with the first change in localization. With subsequent changes in localization, the text of menu items does not change.
Any idea why?

Updated sample for azure file sync?

$
0
0

Is there an updated sample for the Azure File Sync demo that doesn't use deprecated libraries? What are the current recommendations for syncing images?

blog.xamarin.com/sync-files-between-devices-azure-file-sync/

MacOS: Out of nowhere "MSBuild" error.

$
0
0

So yesterday everything was working just fine. But today when I was to open my project it no longer is working. When I try to clean/build I just get the same error Error: Unknown MSBuild failure. Please try building the project again.
I tried to open Xamarin Studio and there the project builds/cleans just fine but in Visual Studio it's not working at all.
I tried googling it and it seems this is a problem, but I found no solutions to it.

Any help is appreciated!

Local Images vs Embedded Images

$
0
0

Is it faster/better to use Local Images or Embedded Images?

*** Local Images: Each project (ios, android, uwp) has the images in the resources folder.
*** Embedded Images:
All images are in a Resource folder in the portable project.

I have 580 images in my portable project, and Im startin to see images not always appearing. So trying to find a solution for what could cause an image not to show up eventhough the .Source property for the Image is set.


Disabled button style

$
0
0

I'm using MVVM approach described here.

To control a button behaviour I use ICommand binding with CanExecute flag. Everything works.

But how can I control disabled button style (background color and text color) in XAML?

Images not always showing

$
0
0

I'm making a game and I've noticed that images do not always display its imagesource. This seems to happen more frequently. I have all images set as Embedded with copy if newer in my project. My project now contains **578 **embedded images. I'm always using the normal Image component.

I get the images with this code:
public static ImageSource GetImage(Images name, ImageType imgType)
{
string key = "PartyTime.Resources." + imgType.ToString() + "." + name + ".png";

        try
        {
            if (m_Images.ContainsKey(key)) return m_Images[key];

            ImageSource img = ImageSource.FromResource(key);

            m_Images.Add(key, img);

            return img;
        }
        catch (Exception ex)
        {
            Classes.Globals.Log("GetImage(2) Ex: " + ex.ToString());
            return ImageSource.FromResource(key);
        }
    }

I cant post images yet with this new account so I'll try to explain it with symbols below. Consider each [tile] as an image. Sometimes an image does not show the image assingned to the imagesource:
[tile][tile][tile][ ][tile]

Any suggestions would be greatly appreciated.

RequestPermissions does not show dialog

$
0
0

Hi

I have been searching for a while now but have not found a solution yet.
I need to request the READ_PHONE_STATE permission.
I have implemented a device specific implementation of my PCL interface IDeviceSettings.

public void RequestPermissions()
{
try
{
if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.Camera) != (int)Permission.Granted)
{
ActivityCompat.RequestPermissions((Activity)Forms.Context, new String[] { Manifest.Permission.ReadPhoneState }, 0);
}
else
{
// Permission has already been accepted previously
}
}
catch (Exception ex)
{
int x = 1 + 1;
}
}

I also implemented the device specific override to check if a permission was granted or not.

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
switch (requestCode)
{
case 0:
{
if (grantResults[0] == Permission.Granted)
{
//Permission granted
int x = 1 + 1;

                    }
                    else
                    {
                        //Permission Denied :(
                        //Disabling location functionality
                        int x = 1 + 1;
                    }
                }
                break;
        }
    }

I then call this from my codebehind xaml view (for quick testing).

private async void Button_Clicked(object sender, EventArgs e)
{
IDeviceSettings deviceSettings = DependencyService.Get();
bool enabled = deviceSettings.AutomaticTimeEnabled();
await DisplayAlert("Output", enabled.ToString(), "OK");

        deviceSettings.RequestPermissions();

        //string hwid = deviceSettings.GetHardwareId();
        //await DisplayAlert("Output", hwid, "OK");
    }

Now i dont get a dialog where i can accept the requested permissions, but the override in MainActivity gets called immediately with Permissions denied.
I also tried launching an activity from android and requesting them there but then i dont even get the callback.

Some more info :

Visual Studio 2017 Community

Minimum Android Version : 4.1 (16)
Target Android Version : 7.1 (25)

Xamarin 4.5.0.486 (fec6f88)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin.Android SDK 7.3.1.2 (9dbc4c5)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK 10.10.0.37 (ad35de4)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Using the Plugin.Permissions from James is not an option since it breaks my app, issue can be found here :
https://github.com/jamesmontemagno/PermissionsPlugin/issues/57#issuecomment-318839270

Any help = greatly appreciated.

Local Notifications Plugin - Image/Logo

DisplayAlert not working

$
0
0

Dears,

I am using DisplayAlert in my project for displaying no internet connection alert. Unfortunately, it is not working.

It working fine in another part. I don't know the reason why it behaves like this.

My code:

               if (Utility.IsInternet())
                {
                    UserTweetsList();
                }
                else
                {
                    Debug.WriteLine("Enter no internet block");
                    DisplayAlert("Alert", "No internet connection", "Ok");
                }

Code enters the else block and prints the "Enter no internet block" in the output, but not displaying the alert message.

What are the possible reasons for this?

Thanks in advance....

Viewing all 89864 articles
Browse latest View live


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