gpt4 book ai didi

java - 如何在自定义 BaseAdapter 中使用自定义字体

转载 作者:行者123 更新时间:2023-12-02 05:21:14 26 4
gpt4 key购买 nike

我正在使用 Android Studio 创建 Android 应用程序。我在使用自定义 SimpleAdapter 的 Activity 中有 ListView 。我需要在自定义适配器中使用自定义字体,但当我尝试时它不起作用。没有错误,只是没有使用字体。直接在 Activity 中使用时,字体路径工作正常。

当我注销创建的字体时,我得到:

E/====﹕ FONT: android.graphics.Typeface@4c5dfbc0

这是我的自定义适配器代码:

package com.myapp.app.utilities;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.fieldly41.app.R;

import java.util.ArrayList;
import java.util.HashMap;

public class SimpleIconAdapter extends SimpleAdapter {

private ArrayList<HashMap<String, String>> results;

//private Context context;

Typeface font;

public SimpleIconAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {

super(context, data, resource, from, to);

this.results = data;

}

@Override
public View getView(int position, View view, ViewGroup parent) {

View v = view;

if (v == null) {

LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

v = inflater.inflate(R.layout.list_item_icon, null);

}

if(results.get(position) != null ) {

Typeface fonter = Typeface.createFromAsset(v.getResources().getAssets(), "fonts/ss-symbolicons-line.ttf");

TextView top_label = (TextView) v.findViewById(R.id.top_label);
TextView icon_label = (TextView) v.findViewById(R.id.icon);
TextView bottom_label = (TextView) v.findViewById(R.id.bottom_label);

icon_label.setText("💀");
icon_label.setTypeface(fonter);

if (results.get(position).get("locked").equals("false")) {

icon_label.setTextColor(Color.WHITE);

} else {

icon_label.setTextColor(Color.RED);

}

top_label.setText(results.get(position).get("title"));
bottom_label.setText(results.get(position).get("created_at"));

}

return v;

}

}

最佳答案

您的实现已接近正常。

但最大的问题是您正在 getView() 方法中创建一个 TypeFace 实例,该实例非常消耗资源。

因为每当您滚动列表时,getView() 方法都会重复调用 N 次。

从 Assets 中广泛加载资源是不好的做法,它随时可能导致 OutOfMemoryError

所以我的建议是创建通用对象并在 getView() 中使用。

public SimpleIconAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {

super(context, data, resource, from, to);
font=Typeface.createFromAsset(context.getAssets(), "fonts/ss-symbolicons-line.ttf");
this.results = data;


}

在 getView() 中删除此行

Typeface fonter = Typeface.createFromAsset(v.getResources().getAssets(), "fonts/ss-symbolicons-line.ttf");

并使用“font”对象代替字体

icon_label.setTypeface(font);

关于java - 如何在自定义 BaseAdapter 中使用自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26505109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com