java如何在自定义BaseAdapter中使用自定义字体
我正在使用Android Studio创建一个Android应用程序。 我在使用自定义SimpleAdapter的活动中有listview。 我需要在自定义适配器中使用自定义字体,但当我尝试时,它不起作用。 没有错误,只是没有使用字体。直接在活动中使用字体路径时效果良好
当我注销创建的fonter时,我得到以下信息:
E/====﹕ FONT: 安卓.graphics.Typeface@4c5dfbc0
这是我的自定义适配器代码:
package com.myapp.app.utilities;
import 安卓.content.Context;
import 安卓.graphics.Color;
import 安卓.graphics.Typeface;
import 安卓.util.Log;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.SimpleAdapter;
import 安卓.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;
}
}
# 1 楼答案
试试这种方法,希望这能帮助你解决问题强>
由于它是一个listview,我建议您创建一个自定义的textview,并将其放入行布局xml中
注意:在
assets
文件夹中放置所需的字体文件非常重要使用自定义字体创建自定义文本视图
自定义文本视图。java
尝试定义自定义文本视图,而不是希望显示自定义字体的简单文本视图
列出项目图标。xml
请注意自定义TextView声明和初始化,并在使用自定义适配器时尝试使用ViewHolder概念
# 2 楼答案
您的实现接近正常
但是最大的问题是,您正在
getView()
方法中创建一个TypeFace
实例,这非常需要资源因为每当您滚动列表时,
getView()
方法重复调用N次从资产中大量加载资源是一种不好的做法,它可能会在任何时候导致
OutOfMemoryError
因此,我的建议是创建公共对象并在getView()中使用
在getView()中删除这一行
并使用“字体”对象代替fonter