Example usage for android.graphics Typeface createFromFile

List of usage examples for android.graphics Typeface createFromFile

Introduction

In this page you can find the example usage for android.graphics Typeface createFromFile.

Prototype

public static Typeface createFromFile(@Nullable String path) 

Source Link

Document

Create a new typeface from the specified font file.

Usage

From source file:Main.java

public static Typeface getTypeface(SharedPreferences pref, String key, String defaultTypeface) {
    Typeface typeface = null;//  www  . j  av  a  2s . c o m
    String fontPath = pref.getString(key, null);
    if (fontPath == null || fontPath.equals(defaultTypeface)) {
        return null;
    } else {
        try {
            typeface = Typeface.createFromFile(new File(fontPath));
        } catch (Exception e) {
        }
    }
    return typeface;
}

From source file:Main.java

public static Typeface getTypeface(Context c, String name) {
    synchronized (typefaces) {
        if (!typefaces.containsKey(name)) {
            try {
                InputStream inputStream = c.getAssets().open(name);
                File file = createFileFromInputStream(inputStream, name);
                if (file == null) {
                    return Typeface.DEFAULT;
                }/*w  w w.  ja  v a2 s  . com*/
                Typeface t = Typeface.createFromFile(file);
                typefaces.put(name, t);
            } catch (Exception e) {
                e.printStackTrace();
                return Typeface.DEFAULT;
            }
        }
        return typefaces.get(name);
    }
}

From source file:com.tr4android.support.extension.typeface.TypefaceCompat.java

@Deprecated
private static void initialize() {
    Log.w("TypefaceCompat",
            "TypefaceCompat is deprecated. Use downloadable fonts or FontsContractCompat instead.");
    if (mTypefaceDetectionEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        Typeface roboto = Typeface.createFromFile(SYSTEM_ROBOTO_REGULAR_FILE_PATH);
        if (roboto != null) {
            mIsUsingDefaultFont = TypefaceUtils.sameAs(roboto, Typeface.SANS_SERIF);
        }/* w  w w  . j a v  a  2s.co m*/
    }
    mInitialized = true;
}

From source file:com.ubergeek42.WeechatAndroid.adapters.ChatLinesAdapter.java

public void setFont(@NonNull String fontPath) {
    typeface = ("".equals(fontPath)) ? null : Typeface.createFromFile(fontPath);
}

From source file:org.liberty.android.fantastischmemo.ui.CardFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.card_layout, container, false);
    cardTextView = (TextView) v.findViewById(R.id.card_text_view);
    rootView = (LinearLayout) v.findViewById(R.id.root);

    cardTextView.setText(mCardText);//ww w. j a  v a  2  s.c  o m

    if (cardOnClickListener != null) {
        rootView.setOnClickListener(cardOnClickListener);
    }

    if (cardOnLongClickListener != null) {
        rootView.setOnLongClickListener(cardOnLongClickListener);
    }

    if (textOnClickListener != null) {
        cardTextView.setOnClickListener(textOnClickListener);
    }

    if (textOnLongClickListener != null) {
        cardTextView.setOnLongClickListener(textOnLongClickListener);
    }

    cardTextView.setTextColor(textColor);

    rootView.setBackgroundColor(backgroundColor);

    if (fontFile != null && new File(fontFile).exists()) {
        Typeface qt = Typeface.createFromFile(fontFile);
        cardTextView.setTypeface(qt);
    }

    cardTextView.setTextSize(fontSize);

    // It is tricky to set up the alignment of the text.
    if (textAlignment == Gravity.CENTER) {
        cardTextView.setGravity(Gravity.CENTER);
        rootView.setGravity(Gravity.CENTER);
    } else if (textAlignment == Gravity.RIGHT) {
        cardTextView.setGravity(Gravity.RIGHT);
        rootView.setGravity(Gravity.NO_GRAVITY);
    } else {
        cardTextView.setGravity(Gravity.LEFT);
        rootView.setGravity(Gravity.NO_GRAVITY);
    }

    return v;
}

From source file:com.obnsoft.ptcm3.MyApplication.java

public Typeface getSBFontTypeFace() {
    Typeface ret = null;//from  w w  w  . j  a v  a2 s.  co m
    try {
        ret = Typeface.createFromFile(getFileStreamPath(FNAME_FONT_TTF));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:com.taobao.weex.utils.TypefaceUtil.java

private static boolean loadLocalFontFile(String path, String fontFamily) {
    if (TextUtils.isEmpty(path) || TextUtils.isEmpty(fontFamily)) {
        return false;
    }/*from  w  w  w .jav a  2  s .  c  o m*/
    try {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        Typeface typeface = Typeface.createFromFile(path);
        if (typeface != null) {
            FontDO fontDo = sCacheMap.get(fontFamily);
            if (fontDo != null) {
                fontDo.setState(FontDO.STATE_SUCCESS);
                fontDo.setTypeface(typeface);
                if (WXEnvironment.isApkDebugable()) {
                    WXLogUtils.d(TAG, "load local font file success");
                }

                Intent intent = new Intent(ACTION_TYPE_FACE_AVAILABLE);
                intent.putExtra("fontFamily", fontFamily);
                LocalBroadcastManager.getInstance(WXEnvironment.getApplication()).sendBroadcast(intent);
                return true;
            }
        } else {
            WXLogUtils.e(TAG, "load local font file failed, can't create font.");
        }
    } catch (Exception e) {
        WXLogUtils.e(TAG, e.toString());
    }
    return false;
}

From source file:com.farmerbb.taskbar.service.TaskbarService.java

@SuppressLint("RtlHardcoded")
private void drawTaskbar() {
    IconCache.getInstance(this).clearCache();

    // Initialize layout params
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    U.setCachedRotation(windowManager.getDefaultDisplay().getRotation());

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            PixelFormat.TRANSLUCENT);/*from   w  ww .  j a va 2  s. c om*/

    // Determine where to show the taskbar on screen
    switch (U.getTaskbarPosition(this)) {
    case "bottom_left":
        layoutId = R.layout.taskbar_left;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        positionIsVertical = false;
        break;
    case "bottom_vertical_left":
        layoutId = R.layout.taskbar_vertical;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        positionIsVertical = true;
        break;
    case "bottom_right":
        layoutId = R.layout.taskbar_right;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        positionIsVertical = false;
        break;
    case "bottom_vertical_right":
        layoutId = R.layout.taskbar_vertical;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        positionIsVertical = true;
        break;
    case "top_left":
        layoutId = R.layout.taskbar_left;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        positionIsVertical = false;
        break;
    case "top_vertical_left":
        layoutId = R.layout.taskbar_top_vertical;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        positionIsVertical = true;
        break;
    case "top_right":
        layoutId = R.layout.taskbar_right;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        positionIsVertical = false;
        break;
    case "top_vertical_right":
        layoutId = R.layout.taskbar_top_vertical;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        positionIsVertical = true;
        break;
    }

    // Initialize views
    int theme = 0;

    SharedPreferences pref = U.getSharedPreferences(this);
    switch (pref.getString("theme", "light")) {
    case "light":
        theme = R.style.AppTheme;
        break;
    case "dark":
        theme = R.style.AppTheme_Dark;
        break;
    }

    boolean altButtonConfig = pref.getBoolean("alt_button_config", false);

    ContextThemeWrapper wrapper = new ContextThemeWrapper(this, theme);
    layout = (LinearLayout) LayoutInflater.from(wrapper).inflate(layoutId, null);
    taskbar = (LinearLayout) layout.findViewById(R.id.taskbar);
    scrollView = (FrameLayout) layout.findViewById(R.id.taskbar_scrollview);

    if (altButtonConfig) {
        space = (Space) layout.findViewById(R.id.space_alt);
        layout.findViewById(R.id.space).setVisibility(View.GONE);
    } else {
        space = (Space) layout.findViewById(R.id.space);
        layout.findViewById(R.id.space_alt).setVisibility(View.GONE);
    }

    space.setOnClickListener(v -> toggleTaskbar());

    startButton = (ImageView) layout.findViewById(R.id.start_button);
    int padding;

    if (pref.getBoolean("app_drawer_icon", false)) {
        startButton.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.ic_launcher));
        padding = getResources().getDimensionPixelSize(R.dimen.app_drawer_icon_padding_alt);
    } else {
        startButton.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.all_apps_button_icon));
        padding = getResources().getDimensionPixelSize(R.dimen.app_drawer_icon_padding);
    }

    startButton.setPadding(padding, padding, padding, padding);
    startButton.setOnClickListener(ocl);
    startButton.setOnLongClickListener(view -> {
        openContextMenu();
        return true;
    });

    startButton.setOnGenericMotionListener((view, motionEvent) -> {
        if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY)
            openContextMenu();

        return false;
    });

    refreshInterval = (int) (Float.parseFloat(pref.getString("refresh_frequency", "2")) * 1000);
    if (refreshInterval == 0)
        refreshInterval = 100;

    sortOrder = pref.getString("sort_order", "false");
    runningAppsOnly = pref.getString("recents_amount", "past_day").equals("running_apps_only");

    switch (pref.getString("recents_amount", "past_day")) {
    case "past_day":
        searchInterval = System.currentTimeMillis() - AlarmManager.INTERVAL_DAY;
        break;
    case "app_start":
        long oneDayAgo = System.currentTimeMillis() - AlarmManager.INTERVAL_DAY;
        long appStartTime = pref.getLong("time_of_service_start", System.currentTimeMillis());
        long deviceStartTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
        long startTime = deviceStartTime > appStartTime ? deviceStartTime : appStartTime;

        searchInterval = startTime > oneDayAgo ? startTime : oneDayAgo;
        break;
    }

    Intent intent = new Intent("com.farmerbb.taskbar.HIDE_START_MENU");
    LocalBroadcastManager.getInstance(TaskbarService.this).sendBroadcast(intent);

    if (altButtonConfig) {
        button = (Button) layout.findViewById(R.id.hide_taskbar_button_alt);
        layout.findViewById(R.id.hide_taskbar_button).setVisibility(View.GONE);
    } else {
        button = (Button) layout.findViewById(R.id.hide_taskbar_button);
        layout.findViewById(R.id.hide_taskbar_button_alt).setVisibility(View.GONE);
    }

    try {
        button.setTypeface(Typeface.createFromFile("/system/fonts/Roboto-Regular.ttf"));
    } catch (RuntimeException e) {
        /* Gracefully fail */ }

    updateButton(false);
    button.setOnClickListener(v -> toggleTaskbar());

    LinearLayout buttonLayout = (LinearLayout) layout.findViewById(
            altButtonConfig ? R.id.hide_taskbar_button_layout_alt : R.id.hide_taskbar_button_layout);
    if (buttonLayout != null)
        buttonLayout.setOnClickListener(v -> toggleTaskbar());

    LinearLayout buttonLayoutToHide = (LinearLayout) layout.findViewById(
            altButtonConfig ? R.id.hide_taskbar_button_layout : R.id.hide_taskbar_button_layout_alt);
    if (buttonLayoutToHide != null)
        buttonLayoutToHide.setVisibility(View.GONE);

    int backgroundTint = U.getBackgroundTint(this);
    int accentColor = U.getAccentColor(this);

    dashboardButton = (FrameLayout) layout.findViewById(R.id.dashboard_button);
    navbarButtons = (LinearLayout) layout.findViewById(R.id.navbar_buttons);

    dashboardEnabled = pref.getBoolean("dashboard", false);
    if (dashboardEnabled) {
        layout.findViewById(R.id.square1).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square2).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square3).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square4).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square5).setBackgroundColor(accentColor);
        layout.findViewById(R.id.square6).setBackgroundColor(accentColor);

        dashboardButton.setOnClickListener(v -> LocalBroadcastManager.getInstance(TaskbarService.this)
                .sendBroadcast(new Intent("com.farmerbb.taskbar.TOGGLE_DASHBOARD")));
    } else
        dashboardButton.setVisibility(View.GONE);

    if (pref.getBoolean("button_back", false)) {
        navbarButtonsEnabled = true;

        ImageView backButton = (ImageView) layout.findViewById(R.id.button_back);
        backButton.setVisibility(View.VISIBLE);
        backButton.setOnClickListener(v -> {
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_BACK);
            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);
        });
    }

    if (pref.getBoolean("button_home", false)) {
        navbarButtonsEnabled = true;

        ImageView homeButton = (ImageView) layout.findViewById(R.id.button_home);
        homeButton.setVisibility(View.VISIBLE);
        homeButton.setOnClickListener(v -> {
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_HOME);
            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);
        });

        homeButton.setOnLongClickListener(v -> {
            Intent voiceSearchIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
            voiceSearchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            try {
                startActivity(voiceSearchIntent);
            } catch (ActivityNotFoundException e) {
                /* Gracefully fail */ }

            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);

            return true;
        });

        homeButton.setOnGenericMotionListener((view13, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                    && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                Intent voiceSearchIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
                voiceSearchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                try {
                    startActivity(voiceSearchIntent);
                } catch (ActivityNotFoundException e) {
                    /* Gracefully fail */ }

                if (pref.getBoolean("hide_taskbar", true)
                        && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                    hideTaskbar(true);
            }
            return true;
        });
    }

    if (pref.getBoolean("button_recents", false)) {
        navbarButtonsEnabled = true;

        ImageView recentsButton = (ImageView) layout.findViewById(R.id.button_recents);
        recentsButton.setVisibility(View.VISIBLE);
        recentsButton.setOnClickListener(v -> {
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_RECENTS);
            if (pref.getBoolean("hide_taskbar", true)
                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                hideTaskbar(true);
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            recentsButton.setOnLongClickListener(v -> {
                U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);
                if (pref.getBoolean("hide_taskbar", true)
                        && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                    hideTaskbar(true);

                return true;
            });

            recentsButton.setOnGenericMotionListener((view13, motionEvent) -> {
                if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                        && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                    U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN);
                    if (pref.getBoolean("hide_taskbar", true)
                            && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                        hideTaskbar(true);
                }
                return true;
            });
        }
    }

    if (!navbarButtonsEnabled)
        navbarButtons.setVisibility(View.GONE);

    layout.setBackgroundColor(backgroundTint);
    layout.findViewById(R.id.divider).setBackgroundColor(accentColor);
    button.setTextColor(accentColor);

    if (isFirstStart && FreeformHackHelper.getInstance().isInFreeformWorkspace())
        showTaskbar(false);
    else if (!pref.getBoolean("collapsed", false) && pref.getBoolean("taskbar_active", false))
        toggleTaskbar();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(showReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(hideReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(tempShowReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(tempHideReceiver);

    LocalBroadcastManager.getInstance(this).registerReceiver(showReceiver,
            new IntentFilter("com.farmerbb.taskbar.SHOW_TASKBAR"));
    LocalBroadcastManager.getInstance(this).registerReceiver(hideReceiver,
            new IntentFilter("com.farmerbb.taskbar.HIDE_TASKBAR"));
    LocalBroadcastManager.getInstance(this).registerReceiver(tempShowReceiver,
            new IntentFilter("com.farmerbb.taskbar.TEMP_SHOW_TASKBAR"));
    LocalBroadcastManager.getInstance(this).registerReceiver(tempHideReceiver,
            new IntentFilter("com.farmerbb.taskbar.TEMP_HIDE_TASKBAR"));

    startRefreshingRecents();

    windowManager.addView(layout, params);

    isFirstStart = false;
}

From source file:com.xlythe.engine.theme.Theme.java

public static Typeface getFont(Context context, String name) {
    String key = getKey(context) + "_" + name;
    if (TYPEFACE_MAP.containsKey(key)) {
        return TYPEFACE_MAP.get(key);
    }/*from ww  w.ja  v a  2s  .  com*/

    String[] extensions = { ".ttf", ".otf" };
    for (String s : extensions) {
        try {
            // Use cursor loader to grab font
            String url = getPackageName() + ".FileProvider/" + name + s;
            Uri uri = Uri.parse("content://" + url);
            ContentResolver cr = context.getContentResolver();
            AssetFileDescriptor a = cr.openAssetFileDescriptor(uri, null);
            FileInputStream in = new FileInputStream(a.getFileDescriptor());
            in.skip(a.getStartOffset());
            File file = new File(context.getCacheDir(), name + s);
            file.createNewFile();
            FileOutputStream fOutput = new FileOutputStream(file);
            byte[] dataBuffer = new byte[1024];
            int readLength = 0;
            while ((readLength = in.read(dataBuffer)) != -1) {
                fOutput.write(dataBuffer, 0, readLength);
            }
            in.close();
            fOutput.close();

            // Try/catch for broken fonts
            Typeface t = Typeface.createFromFile(file);
            TYPEFACE_MAP.put(key, t);
            return TYPEFACE_MAP.get(key);
        } catch (Exception e) {
            // Do nothing here
        }
    }

    TYPEFACE_MAP.put(key, null);
    return TYPEFACE_MAP.get(key);
}

From source file:org.catnut.util.CatnutUtils.java

/**
 * ?????//from www  .j av  a  2  s .c om
 *
 * @param pref
 * @param key
 * @param defaultTypeface
 * @return ??null
 */
public static Typeface getTypeface(SharedPreferences pref, String key, String defaultTypeface) {
    Typeface typeface = null;
    String fontPath = pref.getString(key, null);
    if (fontPath == null || fontPath.equals(defaultTypeface)) {
        return null;
    } else {
        try {
            typeface = Typeface.createFromFile(new File(fontPath));
        } catch (Exception e) {
        }
    }
    return typeface;
}