从url动态加载字体或从lib静态加载字体

时间:2016-07-03 07:04:51

标签: android fonts sdk typeface

我正在运行Android应用程序,我想动态加载字体并在运行时使用它。我怎么能这样做?

另外,我如何在我编写的SDK中包含字体,在我编写的应用程序中引用sdk,并使用SDK中包含的字体?

编辑:感谢您对此投了-1票,无论谁做到了这一点,我都会停止分享知识,这是让我失望的好方法。

1 个答案:

答案 0 :(得分:1)

以下是我将如何做到这一点:(使用AsyncTask,这不是完美的) 如果你想要一个比AsyncTask更稳定的东西RxAndroid提供其他好的变种,那就更稳定了。 在这个例子中,我正在“doInBackground”部分中执行所有操作,但您可以在任务完成后的任何位置以相同的方式使用它。 此示例还假设我们有从外部存储写入和读取的权限。

    private class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // download the file
            input = connection.getInputStream();
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/fonts");
            dir.mkdirs();
            File file = new File(dir, "font.ttf");
            try {
                OutputStream out = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int len;
                while((len=input.read(buf))>0){
                    out.write(buf,0,len);
                }
                out.close();
                input.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            File sdcard = Environment.getExternalStorageDirectory();
            File dirs = new File(sdcard.getAbsolutePath()+"/fonts");

            if(dirs.exists()) {
                File[] files = dirs.listFiles();
                Log.d("s","files");
            }
            final Typeface typeface = Typeface.createFromFile(
                    new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
            Log.d("a","created");
            // Now I'm starting with an example that shows how to use 
            // this font on a textview of my choice.
            // Assumptions: font has characters uF102 and uF104
            final TextView tv = (TextView) findViewById(R.id.myTextView);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (tv != null && typeface != null) {
                        tv.setTypeface(typeface);
                        tv.setText("\uF102");
                        tv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (tv.getText().equals("\uF102")){
                                    tv.setText("\uF104");
                                } else {
                                    tv.setText("\uF102");
                                }
                            }
                        });
                    }
                }
            });

        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
}

如果我们想从我们正在使用的sdk中加载字体,我们可以在可绘制的原始部分中包含该字体,并且从使用此sdk / lib的应用程序中我们可以像这样引用字体: (例如,我在这种情况下使用了amaticobold字体)

        File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath() + "/fonts");
    dir.mkdirs();
    File file = new File(dir, "font.ttf");
    InputStream is = getResources().openRawResource(getResources().getIdentifier("amaticbold","raw", getPackageName()));
    try {
        OutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=is.read(buf))>0){
            out.write(buf,0,len);
        }
        out.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    File sdcard = Environment.getExternalStorageDirectory();
    File dirs = new File(sdcard.getAbsolutePath()+"/fonts");

    if(dirs.exists()) {
        File[] files = dirs.listFiles();
        Log.d("s","files");
    }
    final Typeface typeface = Typeface.createFromFile(
            new File(Environment.getExternalStorageDirectory()+"/fonts", "font.ttf"));
    editText.setTypeface(typeface);