如何在Android Xamarin App中用C#编写等效的Java Enum代码

时间:2016-12-10 14:05:37

标签: android xamarin

以下是代码 这对C#程序员来说很奇怪。

public static enum Font {
        GROBOLD(FontLoader.GROBOLD, "fonts/grobold.ttf");

        private int val;
        private String path;

        private Font(int val, String path) {
            this.val = val;
            this.path = path;
        }

        public static String getByVal(int val) {
            for (Font font : values()) {
                if (font.val == val) {
                    return font.path;
                }
            }
            return null;
        }
    }

这是文件 https://github.com/abhiongithub/memory-game/blob/master/app/src/main/java/com/snatik/matches/utils/FontLoader.java

我没有得到如何在C#中编写等效代码。

1 个答案:

答案 0 :(得分:0)

我现在在我的应用程序中写了这样的内容,作为C#代码

public class FontLoader
    {
        private static SparseArray<Typeface> fonts = new SparseArray<Typeface>();
        private static bool fontsLoaded = false;

        public enum Font
        {
            GROBOLD
        }

        public static void LoadFonts()
        {
            fonts.Put(Convert.ToInt32(Font.GROBOLD), Typeface.CreateFromAsset(Application.Context.Assets, "fonts/grobold.ttf"));
            fontsLoaded = true;
        }

        public static Typeface GetTypeface(Font font)
        {
            if (!fontsLoaded)
            {
                LoadFonts();
            }
            return fonts.Get(Convert.ToInt32(font));
        }

        public static void SetTypeface(TextView[] textViews, Font font)
        {
            SetTypeFaceToTextViews(textViews, font, TypefaceStyle.Normal);
        }

        public static void setBoldTypeface(TextView[] textViews, Font font)
        {
            SetTypeFaceToTextViews(textViews, font, TypefaceStyle.Bold);
        }

        private static void SetTypeFaceToTextViews(TextView[] textViews, Font font,TypefaceStyle fontStyle)
        {
            if (!fontsLoaded)
            {
                LoadFonts();
            }
            Typeface currentFont = fonts.Get(Convert.ToInt32(font));

            for (int i = 0; i < textViews.Length; i++)
            {
                if (textViews[i] != null)
                    textViews[i].SetTypeface(currentFont, fontStyle);
            }
        }
    }