Search code examples
c#androidxamarinxamarin.androidandroidx

Xamarin AndroidX.Preferences - Cannot convert from 'SettingsFragment' to 'Android.Support.V4.App.Fragment'


I'm trying to update the settings/preferences screen of my Xamarin Android app, which was using the PreferenceManager class. Since I'm targeting Android 10, this class is deprecated and I'd like to use the AndroidX.Preference library instead.

I followed Google's guide for making a settings screen with AndroidX. Here's the code I'm using

namespace SmartLyrics
{
    [Activity(Label = "Settings", ConfigurationChanges = Android.Content.PM.ConfigChanges.ScreenSize | Android.Content.PM.ConfigChanges.Orientation, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]
    public class SettingsFragment : PreferenceFragmentCompat
    {
        public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
        {
            AddPreferencesFromResource(Resource.Xml.perfs);
        }
    }

    public class SettingsActivity : AppCompatActivity
    {
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.main_settings);

            SupportFragmentManager
                .BeginTransaction()
                .Replace(Resource.Id.settingsContainer, new SettingsFragment()) //<--error here
                .Commit();
        }
    }
}

I'm getting the error Cannot convert from 'SmartLyrics.SettingsFragment' to 'Android.Support.V4.App.Fragment'. I looked around online and couldn't find a workaround or anything about this error. I'd really like to use the AndroidX library to prevent any problems with unsupported code later on.

Any help is appreciated. Thanks!


Solution

  • Check which package AppCompatActivity refers to ?

    If it:

    using Android.Support.V7.App;
    

    change it to :

    using AndroidX.AppCompat.App;