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

Get device volume

$
0
0

Hey guys,
is it possible to read the volume level of an android device?
There are 3 different volumes: Ringtone, music and alarm. I would like to find, if the music is muted.
I've searched a lot and nothing seems to work.

Thanks for any suggestion ;)


How to create stylized instances of controlls with nested settings?

$
0
0

I am trying to set default styles for elements such as Entry for instance.

Here is how I make the entry on each individual Entry element.

        <Entry
                        x:Name="SerialNumber"
                        Placeholder="Serial"
                        TextTransform="Default"
                        Text="{Binding Path=MyInventoryItem.SerialNumber, Mode=TwoWay}"
                        WidthRequest="150" >
                        <Entry.Keyboard>
                            <Keyboard x:FactoryMethod="Create">
                                <x:Arguments>
                                    <KeyboardFlags>Suggestions,CapitalizeCharacter</KeyboardFlags>
                                </x:Arguments>
                            </Keyboard>
                        </Entry.Keyboard>
                    </Entry>

In my App.xaml I set the following Style entries

    <!--  Styling for normal entry fields  -->
    <Style
        ApplyToDerivedTypes="True"
        CanCascade="True"
        TargetType="Entry">
        <Setter Property="BackgroundColor" Value="{StaticResource Key=cBackgroundColor}" />
        <Setter Property="TextColor" Value="{StaticResource Key=cTextColor}" />
        <Setter Property="PlaceholderColor" Value="{StaticResource Key=cShadowColor}" />
        <Setter Property="FontSize" Value="14" />
        <Setter Property="FontFamily" Value="{StaticResource Key=RobotoMono-Regular}" />
        <Style.Triggers>
            <Trigger TargetType="Entry" Property="IsFocused" Value="True">
                <Setter Property="BackgroundColor" Value="{StaticResource Key=cActiveBackgroundColor}" />
            </Trigger>
        </Style.Triggers>
    </Style>

But I cannot set the advanced setting for the Keyboard settings using this method. Or I should say I have not found a way that will not throw an error.

The only alternative I can think of is to complete this all in the C# code, and then programmatically assign the settings...
I can do this, but was trying to be lazy and not have to re-do a truckload of settings I have created. LOL

    var buttonStyle = new Style(typeof(Entry))
            {
                Setters =
                {

                    new Setter { Property = Entry.BackgroundColorProperty, Value = Resources["cTextColor"] },
                    new Setter { Property = Entry.BackgroundColorProperty, Value = Resources["cTextColor"] },
                    new Setter { Property = Entry.FontFamilyProperty, Value = "RobotoMono-Regular" },
                    new Setter { Property = Entry.FontSizeProperty, Value = Resources["nFontSize"] },
                    new Setter { Property = Entry.PlaceholderColorProperty, Value = Resources["cPlaceHolderColor"] },
                    new Setter { Property = Entry.TextColorProperty, Value = Color.Teal },
                    new Setter { Property = Entry.KeyboardProperty, Value = KeyboardFlags.CapitalizeCharacter | KeyboardFlags.Spellcheck }
                },
                Triggers =
                {
                   new Trigger(typeof(Entry)) 
                   { 
                       Property = Entry.IsFocusedProperty, 
                       Value = true 
                   }

                },
                CanCascade = true,
                ApplyToDerivedTypes = true,
            }

Here's the final rub... How do I create this part of the Style Trigger? I cannot figure out how to make this part work...

<Style.Triggers>
            <Trigger TargetType="Entry" Property="IsFocused" Value="True">
                <Setter Property="BackgroundColor" Value="{StaticResource Key=cActiveBackgroundColor}" />
            </Trigger>
   </Style.Triggers>

Thanks for any advice, or confirmation that I just need to recreate the Style elements programmatically.

SQL Lite query failing

$
0
0

This should be straight forward but apparently its not. I am simply trying to get a list from within an id list in a database table. _connection is already instantiated

public Task<List<TextInfo>> GetTextInfosAsync(List<int> idList)
{
return _connection.Table<TextInfo>().Where(x => idList.Equals(x.Id)).ToListAsync();
}

The error message I get is "row value misused". What gives?

Cheers.

SSO in xamarin forms

$
0
0

Hello, can someone help me with implementing Single sign on in xamarin forms? I couldn't find any examples. Any help is appreciated. Thank you.

Stuck on blank screen while closing the CustomTabs in Android (xamarin forms)

the class has extra properties and how to get it?

$
0
0

I am using AMap to get location.

AMap.MyLocation is typeof Android.Locations.Location

when I run ti there will be extra properties and the Android.Locations.Location is base class.

how to get the extra properties?

as you can see the base class is Android.Locations.Location

but AMap.Map.MyLocation has no the properties

pos2 already change pos1 to false but pos1 cant backgroundcolor? how to notify pos 1

$
0
0
private void SetPos1AnswerBackgroundColor(BindableObject bindableObject)
        {
            this.pos1ValueClicked = true;
            if (pos1ValueClicked == true)
            {
                this.Pos1AnswerBackgroundColor = this.Pos1AnswerBackgroundColor == Color.YellowGreen ? Color.DarkGray : Color.YellowGreen;
            }
            else if (pos1ValueClicked == false)
            {
                this.Pos1AnswerBackgroundColor = Color.DarkGray;
            }

        }
        private void SetPos2AnswerBackgroundColor()
        {
            if (this.pos1ValueClicked == true)
            {
                this.pos1ValueClicked = false;

                this.Pos2AnswerBackgroundColor = this.Pos2AnswerBackgroundColor == Color.Blue ? Color.DarkGray : Color.Blue;
            }
            else
                this.Pos2AnswerBackgroundColor = this.Pos2AnswerBackgroundColor == Color.YellowGreen ? Color.DarkGray : Color.YellowGreen;
        }

xamarin.essential file ficker (PDF)

$
0
0

Team,

Any sample code of a file picker for a PDF file?

I already have xamarin.essential 1.6 referenced in my project


How can I run LocalNotification daily even if the app is closed?

$
0
0

How can I run LocalNotification daily even if the app is closed?

I use
thudugala / Plugin.LocalNotification
https://github.com/thudugala/Plugin.LocalNotification
It works fine even if the app is closed properly, but the daily repetition doesn't work, even when I set the property on
Repeats = NotificationRepeat.Daily, not working, it appears only once on the same day

any help

How can I solve this error? ImageButtonRenderer is an AppCompat widget that can....

$
0
0

How can I solve this error?
I change the shape of the buttons, apparently changes the theme of the button.
12-04 14:15:30.266 E/ThemeUtils(19650): View class crc643f46942d9dd1fff9.ImageButtonRenderer is an AppCompat widget that can only be used with a Theme.AppCompat theme (or descendant).
12-04 14:15:30.283 E/ThemeUtils(19650): View class crc64ee486da937c010f4.ButtonRenderer is an AppCompat widget that can only be used with a Theme.AppCompat theme (or descendant).

iOS project runs but does not loads the app

$
0
0

I have a project which has xamarin forms project with Android, UWP and WPF. Now i am integrating the iOS project by directly adding a blank iOS project from sample xamarin forms project and updating the references required for the application.
Result - My iOS project builds and runs successfully but after the app finishes launch screen it does not progresses further.
If any one has any idea about this issue then please let me know.
Note - there is no app crash it does not loads the main page.

Is there a good XForms barcode scanning other than ZXing?

$
0
0

I was wondering if there is another good barcode scanning library to use for Xamarin.Forms other than ZXing by Redth. It seems ZXing last update was on 2018 and very well possibly might not be updated again. Since iOS launched its version 13 out I'm sure a lot of you know about the view tabbing issues that happened. This ZXing library also experienced the tabbing issue on the barcode view and has no override for us to use. There is a pull request sitting waiting but I dont think this project is abandoned (https://github.com/Redth/ZXing.Net.Mobile/pull/849).


Above is an example of the tabbing issue. If the user swipes down the tab will close and the app wont respond. There is a iOS override fix for this where it sets the control to fullscreen, but we cant access this for ZXing library.

Sudden exception: XALNS7024: System.IO.IOException: There is not enough space on the disk.

$
0
0

Hey!

I have an app for Android and iOS, but I do all my testing on my own physical device. A couple of hours this worked, but suddenly I get this exception when I build my solution and I have no idea where this comes from and how to solve this:

XALNS7024: System.IO.IOException: There is not enough space on the disk.

Note that I'm not using an emulator, but a physical device.

Stack trace:
XALNS7024: System.IO.IOException: There is not enough space on the disk.

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at Xamarin.Android.Tools.Files.CopyIfChanged(String source, String destination)
at Xamarin.Android.Tasks.MonoAndroidHelper.CopyAssemblyAndSymbols(String source, String destination)
at Xamarin.Android.Tasks.LinkAssembliesNoShrink.RunTask()
at Xamarin.Android.Tasks.AndroidTask.Execute() 0

Can someone help?

How to do slider with 2 points

$
0
0

I want to do slider filter , must to select form number for another number .
how to do in one slider

Remove Shell Flyout Hamburguer Button WITHOUT disabling Flyout

$
0
0

I currently have this in my AppShell:

<Shell
    x:Class="Fighter_MoveList.AppShell"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:local="clr-namespace:Fighter_MoveList.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="Fighter_MoveList"
    FlyoutBehavior="Flyout"
    FlyoutIcon=""
    FlyoutIsPresented="False"
    mc:Ignorable="d">

    <!--
        Styles and Resources
    -->
    <Shell.Resources>
        <ResourceDictionary>
            <Style x:Key="BaseStyle" TargetType="Element">
                <Setter Property="Shell.BackgroundColor" Value="{StaticResource PrimaryColor}" />
                <Setter Property="Shell.ForegroundColor" Value="White" />
                <Setter Property="Shell.TitleColor" Value="White" />
            </Style>
            <Style BasedOn="{StaticResource BaseStyle}" TargetType="ShellItem" />
        </ResourceDictionary>
    </Shell.Resources>
    <local:RosterPage />
</Shell>

This allows my app to work but it shows a hamburguer button with no content in Android and UWP.
UWP:

I could change the FlyoutBehavior to disabled but this removes the back buttons on UWP, so that's not an option unfortunately.
I tried to change the FlyoutIcon to an empty string hoping the icon would disappear but it didnt.


how can i upload backup of sqlite db to the google drive, and restore it?

$
0
0

I am new to using Google Drive API, I tried some samples but it didn't work well
like this:
https://github.com/stevenchang0529/XamarinGoogleDriveRest
It works fine, but when I try to log in, I get this message:
Error 400: redirect_uri_mismatch

Code:
`
public class MainViewModel : INotifyPropertyChanged
{
private string scope = "https://www.googleapis.com/auth/drive.file";
private string clientId = "clientId here";
private string redirectUrl = "xamarin.test.driverest:/oauth2redirect";

    public event PropertyChangedEventHandler PropertyChanged;

    public ICommand OnGoogleDrive { get;  set; }

    public MainViewModel()
    {
        var auth = new OAuth2Authenticator(
          this.clientId,
          string.Empty,
          scope,
          new Uri("https://accounts.google.com/o/oauth2/v2/auth"),
          new Uri(redirectUrl),
          new Uri("https://www.googleapis.com/oauth2/v4/token"),
          isUsingNativeUI: true);
        AuthenticatorHelper.OAuth2Authenticator = auth;
        auth.Completed +=async  (sender, e) =>
        {
            if (e.IsAuthenticated)
            {

                var initializer = new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets()
                    {
                        ClientId = clientId,
                    }
                };
                initializer.Scopes = new[] { scope };
                initializer.DataStore = new FileDataStore("Google.Apis.Auth");
                var flow = new GoogleAuthorizationCodeFlow(initializer);
                var user = "DriveTest";
                var token = new TokenResponse()
                {
                     AccessToken=e.Account.Properties["access_token"],
                     ExpiresInSeconds=Convert.ToInt64( e.Account.Properties["expires_in"]),
                     RefreshToken=e.Account.Properties["refresh_token"],
                     Scope=e.Account.Properties["scope"],
                     TokenType=e.Account.Properties["token_type"]
                };
                UserCredential userCredential = new UserCredential(flow, user, token);
                var driveService = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = userCredential,
                    ApplicationName = "XamarinDriveTest",
                });


                //test google drive
                DriveServiceHelper helper = new DriveServiceHelper(driveService);
                var id=await helper.CreateFile();
                await helper.SaveFile(id, "test", "test save content");
                var content =await helper.ReadFile(id);
            }
        };
        auth.Error += (sender, e) =>
        {

        };

        this.OnGoogleDrive = new Command(() =>
          {
              var presenter = new OAuthLoginPresenter();
              presenter.Login(auth);
          });
    }
}

public static class AuthenticatorHelper
{
    public static OAuth2Authenticator OAuth2Authenticator { get; set; }
}

`

Using flashlight while camera is on

$
0
0

I have an app with a barcodescanner and an in-app camera.

I have an option in the barcodescanner (using ZXing) for a flashlight, which can be turned on and off in the page itself. The code I'm using to do this is:

Where 'scanner' is the barcodescanner and ButtonFlashlight the button to turn the flash on and off. You can also see that two images are used: one for the off state and one for the on state.

Now I want to implement this in my in-app camera as well, but I cannot get it to work. The latest 'failure' is an exception:

I understand the exception, I just don't know how to do it then.

For using this function in the in-app camera, I used Xamarin.Essentials with this code:

So what I need are two things: first the option to turn on the flashlight, and secondly the check if the flashlight is on or off (so that the correct flashlight image can be shown).

Does someone know how to do this?

How to dynamically change background color with button?

$
0
0

Hi All,

How do I code a button to dynamically change the Stack layout background color on my xamarin Android app? I currently only have a single view and an empty event handler for when the button is clicked. I would like the user to click the button and have the background change color. When the button is clicked again, I would like the button to return to its original color.

Thanks.

Web Service doesn’t work when I try to update the android widget if the app is killed.

$
0
0

We are developing android widget for Xamarin.Forms application. The widget updates and gets data from the Web Service when the app is in Background, but stops working when the app is killed/closed. I have followed this article for developing this widget -
https://stackoverflow.com/questions/53659897/xamarin-android-widget-with-timer-stops-when-app-killed

I want to Update the widget when the user clicks on Refresh button. If I add hardcoded data for textboxes and click Refresh it updates the time but doesn’t work if I assign web service result data for the textboxes. I have added internet permission in AndroidManifest.xml. Is there a way I can get the data from web service even when the app is closed? Or Probably I am missing some permission?

AppWidget.cs -

public static class WidgetConsts
{
public const string DebugTag = "com.myapp.WIDGET";
public const string ActionWakeup = "com.myapp.WIDGET_WAKEUP";
public const string ActionWidgetUpdate = "android.appwidget.action.APPWIDGET_UPDATE";
public const string ActionWidgetDisabled = "android.appwidget.action.APPWIDGET_DISABLED";
}

[BroadcastReceiver]
[IntentFilter(new string[] { WidgetConsts.ActionWakeup })]
public class AlarmReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action.Equals(WidgetConsts.ActionWakeup))
        {
            Log.Debug(WidgetConsts.DebugTag, "Wakeup alarm called");
            if (AppWidget.widgetTimer == null)
            {
                Log.Debug(WidgetConsts.DebugTag, "Widget updating does not run, enforcing update...");
                AppWidget.UpdateAppWidget(context);

            }
            else
            {
                Log.Debug(WidgetConsts.DebugTag, "Widget updating runs, no action needed");
            }
        }
    }
}

[BroadcastReceiver]
[IntentFilter(new string[] { WidgetConsts.ActionWidgetUpdate})]
[MetaData("android.appwidget.provider", Resource = "@xml/appwidget_provider")]
public class AppWidget : AppWidgetProvider
{
    public static System.Timers.Timer widgetTimer = null;
    public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
    {
        RemoteViews views = BuildRemoteViews(context, appWidgetIds);
        (AppWidgetManager.GetInstance(Android.App.Application.Context)).UpdateAppWidget(new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(AppWidget))), views);
       // appWidgetManager.UpdateAppWidget(appWidgetIds[0], views);

        // set timer for updating the widget views each 5 sec
        if (widgetTimer == null)
        {
            widgetTimer = new System.Timers.Timer();
            widgetTimer.Interval = 5000;
            widgetTimer.Elapsed += OnTimedEvent;
        }
        widgetTimer.Enabled = true;

        // set alarm to wake up the app when killed, each 60 sec
        // needs a fresh BroadcastReceiver because AppWidgetProvider.OnReceive is
        // not virtual and overriden method in this class would not be called
        AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
        Intent ai = new Intent(context, typeof(AlarmReceiver));
        ai.SetAction(WidgetConsts.ActionWakeup);
        PendingIntent pi = PendingIntent.GetBroadcast(context, 0, ai, PendingIntentFlags.UpdateCurrent);
        am.SetRepeating(AlarmType.ElapsedRealtime, 100, 1000 * 60, pi);
    }

    public override void OnEnabled(Context context)
    {
        AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
        Intent ai = new Intent(context, typeof(AlarmReceiver));
        ai.SetAction(WidgetConsts.ActionWakeup);
        PendingIntent pi = PendingIntent.GetBroadcast(context, 0, ai, PendingIntentFlags.UpdateCurrent);
        am.SetRepeating(AlarmType.ElapsedRealtime, 100, 1000 * 60, pi);

        base.OnEnabled(context);
    }

    public override void OnDisabled(Context context)
    {
        Log.Debug(WidgetConsts.DebugTag, "Disabling the widget");
        if (widgetTimer != null)
        {
            Log.Debug(WidgetConsts.DebugTag, "Stopping timer");
            widgetTimer.Enabled = false;
        }
        else
            Log.Debug(WidgetConsts.DebugTag, "Timer is null");
        base.OnDisabled(context);
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Log.Debug(WidgetConsts.DebugTag, "Updating status...");
        new Handler(Looper.MainLooper).Post(() =>
        {
            //Run my code to periodically update the widget
            RemoteViews views = new RemoteViews(Android.App.Application.Context.PackageName, Resource.Layout.SnapVertWidget);
            AppWidgetManager manager = AppWidgetManager.GetInstance(Android.App.Application.Context);
            ComponentName thisWidget = new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(AppWidget)));
            int[] appWidgetIds = manager.GetAppWidgetIds(thisWidget);

            (AppWidgetManager.GetInstance(Android.App.Application.Context)).UpdateAppWidget(new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(AppWidget))), views);

           // manager.UpdateAppWidget(appWidgetIds[0], views);
        });
    }

    static public void UpdateAppWidget(Context context)
    {
        Intent intent = new Intent(context, typeof(AppWidget));
        intent.SetAction(WidgetConsts.ActionWidgetUpdate);
        int[] ids = AppWidgetManager.GetInstance(context).GetAppWidgetIds(new ComponentName(context, Java.Lang.Class.FromType(typeof(AppWidget))));
        intent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, ids);
        context.SendBroadcast(intent);
    }

    public RemoteViews BuildRemoteViews(Context context, int[] appWidgetIds)
    {

        Excercise.Droid.Services.WeatherWidget weatherWidget = new Excercise.Droid.Services.WeatherWidget();
        var entry = weatherWidget.GetCurrentWeather();

        // Build an update that holds the updated widget contents
        var updateViews = new RemoteViews(context.PackageName, Resource.Layout.SnapVertWidget);

        updateViews.SetTextViewText(Resource.Id.txtvwUpdate, Convert.ToString(DateTime.Now)); updateViews.SetTextViewText(Resource.Id.txtvwCityName, entry.Result.CityName);
        updateViews.SetTextViewText(Resource.Id.txtvwTemp, entry.Result.TempValue);


        //SetTextViewText(widgetView);
        RegisterClicks(context, appWidgetIds, updateViews);

        return updateViews;

    }
    private void RegisterClicks(Context context, int[] appWidgetIds, RemoteViews widgetView)
    {
        Intent intentUpdate = new Intent(context, typeof(AppWidget));
        intentUpdate.SetAction(AppWidgetManager.ActionAppwidgetUpdate);

        //Update the current widget instance only, by creating an array that contains the widget’s unique ID// 

        int[] idArray = new int[] { appWidgetIds[0] };
        intentUpdate.PutExtra(AppWidgetManager.ExtraAppwidgetIds, idArray);
        PendingIntent pendingUpdate = PendingIntent.GetBroadcast(
          context, appWidgetIds[0], intentUpdate,
          PendingIntentFlags.UpdateCurrent);
        widgetView.SetOnClickPendingIntent(Resource.Id.btnRefresh, pendingUpdate);

        Intent launchAppIntent = new Intent(context, typeof(MainActivity));
        PendingIntent launchAppPendingIntent = PendingIntent.GetActivity(context, 0, launchAppIntent, PendingIntentFlags.UpdateCurrent);
        widgetView.SetOnClickPendingIntent(Resource.Id.pnlWeather, launchAppPendingIntent);

           }
}

How can I make an Observable Collection persistent?

$
0
0

Hi All,

I have am using an Observable Collection to hold a list of entries in my notepad app.

public ObservableCollection<string> ListItem { get; set; } public string Items { get; set; } public MainPageViewModel() { ListItem = new ObservableCollection<string>(); }

I have ICommands which add and remove items to the collection.
How can I make this list persistent?

Thanks.

Viewing all 76418 articles
Browse latest View live


Latest Images

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