简体   繁体   中英

Using a Resources/drawable file as small icon for Notifications in Xamarin.Forms

In a Xamarin.Forms project I have a file icon.png in each of the Resources/drawable folders of the droid project. BuildAction is AndroidResource. I use this file in various places in the project and they appear just fine.

Now I am trying to use it as the small icon for notifications. In the PCL project the small icon is set like this in the example code I am using:

.SetSmallIcon(Android.Resource.Drawable.SymActionEmail)

I was sort of expecting icon to be shown in the Resource.Drawable Intellisense chooser, but it is not, so Android.Resource.Drawable.icon results in 'Resource.Drawable' does not contain a definition for 'icon' .

I tried adding a resx file to the PCL project, but VS will only let me add strings to that file, not images.

How do I use icon instead of SymActionEmail ?

Use Resource.Drawable.icon instead of Android.Resource.Drawable.icon . With the Android prefix, you're referring to this list of predefined resources, not the ones in your project.

Edit: Instead of commenting, I decided to write here because it's easier to read.

SetSmallIcon() is a method in the Notification.Builder class from the Android API. You should never call platform specific code directly from the PCL project. Also, that's the reason you shouldn't even be able to call Android.Resource.Drawable resources from the PCL. Have you added a reference to Xamarin.Android or something?

The correct way to call platform specific code from a PCL is to (for example) create an interface in the PCL, which is then implemented in each platform specific project. Here's an excerpt from the Xamarin documentation:

Using either interfaces or base classes defined in the shared code and implemented or extended in platform-specific projects. Writing and extending shared code with class abstractions is particularly suited to Portable Class Libraries because they have a limited subset of the framework available to them and cannot contain compiler directives to support platform-specific code branches.

Handling Platform Divergence & Features

Also, to your question about setting the notification inside the PCL: Doesn't setting the notification inside one of the platform specific projects sort of break the purpose of using Xamarin.Forms in the first place?

In short, no it doesn't. Xamarin.Forms isn't meant to be able to do everything in a single project, that's why you still have separate projects for iOS, Android and UWP. Anything that requires platform specific libraries or functinality should be implemented in the platform specific project but can still be called from the PCL by using abstraction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM