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

Increase AppBarButton height in UWP

$
0
0

I am trying to modify the style of the AppBarButton, but I have got no luck in trying to override the base style in App.xaml. I believe, I need to set this style at runtime to take effect, but I don't know how to do that. Is there any other way, like using a custom renderer?
Something like this:

public class WindowsContentPageRenderer : PageRenderer
   {
       protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
       {
           base.OnElementChanged(e);
           if (e.OldElement != null && Element == null)
               return;
           Loaded += OnLoaded;
       }

       private void OnLoaded(object sender, RoutedEventArgs args)
       {
           var myPanel = ContainerElement as AppBarButton;
           if (myPanel != null)
           {
               myPanel.Height = 48;
               myPanel.MaxHeight = 48;
           }
       }
   }

But, the ContainerElement as AppBarButton always returns a null.

Please help, thank you :smile:


Xamarin Forms: How to get the SwipeDirection value from SwipeStarted event?

$
0
0

I am using swipeview feature on my project for swiping the flowlistviews. I need both the left and right swipe for my center flowlistview. How can I achieve this on swipeview?

My code:

<SwipeView
    x:Name="SwipeView2"
    SwipeStarted="CenterSwipeView"
    IsVisible="False">
    <SwipeView.RightItems>
        <SwipeItems>
            <SwipeItem/>
        </SwipeItems>
    </SwipeView.RightItems>
    <flv:FlowListView>
        //listview items
    </flv:FlowListView>
</SwipeView>

public void CenterSwipeView(object sender, SwipeStartedEventArgs args)
{
  //how can I get the SwipeDirection value here
}

I need to call different functions based on the SwipeDirection value(left or right).
Also, I tried SwipeGestureRecognizer but it is not working for flowlistview.

Image not showing inXamarin Forms ImageCircle plugin

$
0
0

I am working on a Android App using Xamarin Forms. I have ImageCircle plugin added on my form to display profile image. I want to update it with the photo captured from the phone's camera. So to do this i have these pieces of code.

1. XAML

 <controls:CircleImage x:Name="ImgProfile" BorderColor="DarkSlateGray" BorderThickness="5"  Aspect="AspectFit"  Scale="0.6" HeightRequest="150" WidthRequest="150" />
                            <ImageButton Source="pan.png" BackgroundColor="Transparent" Clicked="ImageButton_Clicked"></ImageButton>

2. C#

async void TakePhoto()
        {
            await CrossMedia.Current.Initialize();
            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Small,
                Name = Guid.NewGuid().ToString().Substring(0,8),
                Directory= "profile"
            });

            if(file==null)
            {
                return;
            }

            ImgProfile.Source=  ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                return stream;
            });
      /* tried this as well

var byteArray = File.ReadAllBytes(file.Path);

        ImgProfile.Source=  ImageSource.FromStream(()=> new MemoryStream( byteArray));

*/

        }

        private void ImageButton_Clicked(object sender, EventArgs e)
        {
            TakePhoto();

        }

I tried below ways as well, but no success:

  1. Setting Source = file.Path

  2. Using Byte Array

  3. {Binding ImageSource} in xaml and setting imagesource in code behind.

The above code is running fine, I can see byte array/stream as well in watch window.But still, Image is not displaying.

Please Note:

My approach is old school WinForm way not MVVM.

Plugins / Modules version

  1. VS 2019 Community 16.5.5

  2. Xamarin Android SDK - 10.2.0.100

  3. Xamarin.Forms 4.6.0.800

  4. Xamarin.Plugin.Media 5.0.1
  5. Xamarin.Plugins.Forms.ImageCircle 3.0.0.5

Thanks in Advance

Firebase app giving 'default firebaseapp is not initialized in this process' error

$
0
0

Hello guys.
I have an app that I am developing and that has been working fine for a long time now and the other day I tried to modify it to upload an update and I started gettting this error:

**Java.Lang.IllegalStateException:** 'Default FirebaseApp is not initialized in this process XXXXX. Make sure to call FirebaseApp.initializeApp(Context) first.'

I get the error when I run the app.

This is my MainActivity.cs

[Activity(Label = "XXXXX", Icon = "@mipmap/icon", MainLauncher = true, Theme = "@style/MainTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
#if DEBUG
            Android.Webkit.WebView.SetWebContentsDebuggingEnabled(true);
#endif
            base.OnCreate(savedInstanceState);

            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            XF.Material.Droid.Material.Init(this, savedInstanceState);

            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                var mChannel = new NotificationChannel("XXXXX", "XXXXX", NotificationImportance.Default);
                mChannel.Description = "Notificaciones de la APP";
                AudioAttributes audioAttributes = new AudioAttributes.Builder().SetContentType(AudioContentType.Sonification).SetUsage(AudioUsageKind.Notification).Build();
                Android.Net.Uri sound1 = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                mChannel.SetSound(sound1, audioAttributes);
                mChannel.EnableVibration(true);
                mChannel.SetVibrationPattern(new long[] { 800 });
                mChannel.ShouldVibrate();
                mChannel.EnableLights(true);
                mChannel.ShouldShowLights();
                var notificationManager = GetSystemService(NotificationService) as NotificationManager;
                notificationManager.CreateNotificationChannel(mChannel);

                FirebasePushNotificationManager.DefaultNotificationChannelId = "XXXXX";
                FirebasePushNotificationManager.DefaultNotificationChannelName = "XXXXX";
            }


            FirebasePushNotificationManager.IconResource = Resource.Drawable.firebase1;


            Android.Net.Uri sound = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
            FirebasePushNotificationManager.SoundUri = sound;

#if DEBUG
            FirebasePushNotificationManager.Initialize(this, true, false);

#else
            FirebasePushNotificationManager.Initialize(this, false, false);
#endif

            LoadApplication(new App());



            Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
            Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);

            Window.SetStatusBarColor(Android.Graphics.Color.Rgb(0, 72, 224));
        }
}

My AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="13" android:versionName="1.4" package="XXXXX" android:installLocation="auto">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29" />
    <application android:label="XXXXX" android:icon="@mipmap/icon" android:usesCleartextTraffic="true" android:roundIcon="@mipmap/icon_round">
        <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/firebase1" />
        <service android:name="XXXXX.MyFirebaseMessagingService" android:stopWithTask="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

I am using the https://github.com/CrossGeeks/FirebasePushNotificationPlugin plugin to handle Firebase Notifications.

Any help is appreciated.
Thank You.

how to Upload file To Web service ?

$
0
0

Hi
I trying to upload files from the mobile app using Web Service.
But after Pick File I could not send the file to the web service
Suppose the web service is located at the following address:
www.haythamweb.com/myServices.asmx/uploadfiles
And I have two parameters:
byte[] fileContent, string fileName

This is the code for the web service:
[WebMethod]
public string UploadFile(byte[] fileContent, string fileName)
{
try
{
MemoryStream ms = new MemoryStream(fileContent);
FileStream fs = new FileStream
(System.Web.Hosting.HostingEnvironment.MapPath
("~/TransientStorage/") +
fileName, FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
return "OK";
}
catch (Exception ex)
{
// return the error message if the operation fails
return ex.Message.ToString();
}
}

This is the code for the upload button I could not complete:

private async void Button_Clicked(object sender, EventArgs e)
{
var file = await CrossFilePicker.Current.PickFile();

        if (file != null)
        {
            lbl.Text = file.FileName ;
        }

        String URI = "http://haythamweb.com/myServices.asmx/uploadfiles";
       ...........................
       ...........................
       ...........................
       ...........................
    }

can you help me

Navigation back button accessibility name

$
0
0

If you have enabled the navigation page, with the back button (the "<" icon) and the title, when the screen reader focus is on the back button it read "unlabeled button". Is there a way to change is Accessibility name to a proper "back button" or whatever else? Either in Android and iOS

iOS Xamarin.Forms.Editor does not scroll

$
0
0

Hi
I am using Xamarin.Forms.Editor with height request given.
When I edit it or enter new line I am able to scroll till end.
But when we launch it with pre-filled text (where text is more than its height) then it does not scroll and only few lines are visible.
If we edit and add some more lines to text, then it enables its scroll, but not on launch.

        var stackEditor = new StackLayout()
                             {
                                  BackgroundColor = Color.LightGray,
                                  Padding = 1,
                                  HeightRequest = 80,
                                 Margin = new Thickness(10, 30, 10, 10),
                                  VerticalOptions = LayoutOptions.Start
                              };

        var textEditor = new Editor()
                         {
                             FontSize = 15,
                             Keyboard = Keyboard.Text,
                             HeightRequest = 80,
                             BackgroundColor = Color.White,
                         };

        textEditor.Text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14";
        stackEditor.Children.Add(textEditor);

        Content = stackEditor;

Here on launch of the editor we can not go to more than 5 number.

Anyone knows the solution for this?

Send POST query from WebView

$
0
0

I need to use JavaScript on WebView. Also it would be great if someone will tell me how to allow send POST queries from WebView to server.
I need it to use some payment system.

If there could be only separate solution for Android and iOS it also would be great if you can tell me how to make it done.


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.

Binding Command in ListView ItemTapped

$
0
0

Hi,

I have a button which opens the Camera using a class called CameraModel. This is done with a Binding Command.

Button to open Camera:

Part of CameraModel.cs:

Besides that, I also have a ListView with several items. I use ItemTapped, where only one of the items performs something when tapped:

Now I face the following problem as you already see in the previous picture:
I want to call CameraModel.cs from one specific ListView Item.
For example:

Text1
Text2
Text3
Text4
Text5

When ‘Text3’ is tapped, you can see that the DisplayAlert will show something, but now I want to add that when I tap ‘Text4’ the Camera will be opened (using CameraModel).

I have no idea how to add the Binding Command to one specific ListView Item, or how to change the code so that a Binding Command is not needed.

How can I do this?

Hope someone can help.

Regards, Ganesh

Xamarin.Forms and Firebase Database - How to Read and Write Data?

$
0
0

Hi all,
I have many problem to read data from a simple Firebase DB and to store it.
It's the first time that I use it so any help will be appreciated.

This is my DB Structure:

I need to read and write the "number" value stored.

I add all Firebase package like Firebase.Database and Firebase.Connection

In my Android Prj I have a class with these:

MainActivity.cs
private void InitFirebaseAuth()
{
var options = new FirebaseOptions.Builder()
.SetApplicationId("******")
.SetApiKey("*******")
.SetDatabaseUrl("******")
.Build();
if (app == null)
app = FirebaseApp.InitializeApp(this, options, "SaloneB");

        }

FirebaseHelper.cs
DatabaseReference databaseReference;
FirebaseDatabase database

    public void Connect()
    {
        database = FirebaseDatabase.GetInstance(MainActivity.app);
    }

First I call Connect then I try something like this without result:
FirebaseClient firebase = new FirebaseClient("*****");
var items = await firebase
.Child("number_of_user")
.OnceAsync();

        foreach (var item in items)
        {
            Person person = new Person();
            person.number = item.Object.number;

        }

Items is 0 elements

What's the best and easiest way to implement PayPal in a Xamarin Forms App?

$
0
0

Hi guys,

I would like to allow paypal, what's a good and easy way to do in Xamarin Forms?

Best regards
Chris

Error when trying to use global colors

$
0
0

Hi,

I have the following code in my "App.xaml"

<Application.Resources>
    <ResourceDictionary>
      <Color x:Key="BackgroundBlue">#334E9D</Color>
      <Color x:Key="ButtonOrange">#F1881E</Color>
        <Setter Property="BackgroundColor" Value="ButtonOrange" />
        <Setter Property="CornerRadius" Value="50px" />
        <Setter Property="BorderColor" Value="ButtonOrange" />
        <Setter Property="BorderWidth" Value="2px" />
        <Setter Property="FontAttributes" Value="Bold" />
        <Setter Property="TextColor" Value="White" />
      </Style>
      <Style TargetType="ContentPage" ApplyToDerivedTypes="True">
        <Setter Property="BackgroundColor" Value="BackgroundBlue" />
      </Style>
    </ResourceDictionary>
  </Application.Resources>

But I am getting the following error

Cannot convert "ButtonOrange" into Xamarin.Forms.Color

Any advice on how to fix this would be great.

Thanks in advance!

Apple SignIn Xamarin.Forms iOS. The Apple ID credential is revoked.

$
0
0

For some reason, I always have empty data

How to use Oauth2 in xamarin form?

$
0
0

I create login form and i want to using Oauth2, Can you give me a specific example? thanks you very much!


Android Custom Renderer is not changing height after PropertyChangedEvent

$
0
0

Hi,

there are 2 views on a page. The views are inside a StackLayout. The views are Grids. One Row of the Grid is MyView which is renderer by a custom renderer.
By clicking onone view the properties of the MyView is swapped. MyView one is displaying the content of MyView two and the other way around.
However, after changing the property the height of MyView is not adjusted correctly to it's content depending on their property. My View is keeping the height of MyView from it's previous content.

I think the problem is inside the custom renderer which is not changing the height of MyView correctly after a PropertyChangedEvent.

[assembly: ExportRenderer(typeof(MyView), typeof(MyViewDroidRenderer))]
namespace pnyxnetmobile.Droid.Renderer
{
    public class DroidRenderer : ViewRenderer
    {
        private MyLinearLayoutBuilderAndroid _builder;

        public DroidRenderer(Context context) : base(context)
        {
            //Init Builder
            _builder = new MyLinearLayoutBuilderAndroid(context);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                MyView view = e.NewElement as MyView;
                //Generate a LinearLayout
                SetNativeControl(_builder.GenerateLinearaLayout(view));
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            MyView view = sender as MyView;
            //Value is the property which is changed
            if (MyView.ValueProperty.PropertyName.Equals(e.PropertyName))
            {
                if (view != null){
                    SetNativeControl(_builder.GenerateLinearaLayout(view));
                    Control.RequestLayout();
                }
            }
        }
    }
}

InsertAsync Xamarin Invalid data type provided

$
0
0

I have a problem with the InsertAsync function. I hope I'm not disturbing. The object I'm trying to insert is called User, it has 3 properties Id, username & password. When I call the InsertAsync() method (without giving any id and having the ID autoincrement on and IDENTITY_INSERT OFF) it throws an invalid data type provided error. If I delete the identity on id and I set an id value from the code it works. But I want it to work with the autoincrement method. Thank you!

Zoom-function for Cross-platform-project (Android, IOS, UWP)

Cannot distribute the APK - Missing input APK

$
0
0

Using VS 16.5.4. Everything builds OK, I can archive an APK, but signing (choosing "Distribute" in the Archive Manager) fails with "Signing packages failed. Missing input APK".
Another strange thing is that when I fill in my key store information in the Android project properties ("Android Package Signing") the build fails with the "key store has been tampered with" error. I have used the same key store for long time and at least 3 or 4 different projects.

Xamarin.Diagnostics window shows:
"Xamarin.AndroidTools.AndroidSdkToolException: Missing input APK

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Xamarin.VisualStudio.Android.Services.Publishing.AndroidToolsPublishService.d__4.MoveNext() in E:\A_work\548\s\src\Core\VisualStudio.Android\Services\Publishing\AndroidToolsPublishService.cs:line 41"

Settings from the Android.csproj file:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <AndroidUseSharedRuntime>false</AndroidUseSharedRuntime>
    <AndroidLinkMode>None</AndroidLinkMode>
    <AndroidSupportedAbis>arm64-v8a</AndroidSupportedAbis>
    <EmbedAssembliesIntoApk>true</EmbedAssembliesIntoApk>
    <AndroidLinkTool>proguard</AndroidLinkTool>
    <AndroidEnableMultiDex>false</AndroidEnableMultiDex>
    <AndroidPackageFormat>apk</AndroidPackageFormat>
    <AndroidDexTool>dx</AndroidDexTool>
    <EnableProguard>true</EnableProguard>
    <AndroidUseAapt2>false</AndroidUseAapt2>
    <AndroidCreatePackagePerAbi>false</AndroidCreatePackagePerAbi>
  </PropertyGroup>

Preferences and Injection

$
0
0

I'm changing my settings to use new Essential Preferences. In past I've always had a static library for my app settings, this causes hardcoded static variables all over the place in my app which has caused me a bit of grief. I'm doing a bunch of training and makes me question this.

So should I be creating an IPreferences, putting all my settings there, and Dependcy Injecting this throughout? Is that the better way?

Thanks.
Brent

Viewing all 89864 articles
Browse latest View live


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