【问题标题】:How to change font in suggestions of an AutocompleteTextview?如何更改 AutocompleteTextview 建议中的字体?
【发布时间】:2013-10-05 14:58:14
【问题描述】:

我正在尝试更改通过 ArrayAdapter 创建的 AutocompleteTextView 建议的字体

Wadapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);

我查找了文件 simple_dropdown_item_1line.xml 并将其传输到我的布局文件夹。这是它的内容:

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@android:id/text1"
style="?android:attr/dropDownItemStyle"
android:textAppearance="?android:attr/textAppearanceLargePopupMenu"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee" />

这样可以轻松更改建议的大小等。但是不能从 xml 更改字体类型(基本字体选项除外),这需要从代码中完成。我尝试使用这行代码:

TextView scroll= (TextView) findViewById(android.R.id.text1);
Typeface type = Typeface.createFromAsset(getAssets(),"Typewriter.ttf");
scroll.setTypeface(type);

但最后一行给了我 NullPointerException。有人知道如何进行吗?

【问题讨论】:

  • 哪一行抛出NPE?
  • 最后一个,也就是textview好像是null...

标签: android fonts android-arrayadapter autocompletetextview typeface


【解决方案1】:

您可以制作一个自定义适配器,并在那里为建议分配一个新字体。

public class CustomAdapter extends ArrayAdapter<String> {

    private Context context;
    private int layout;
    private final Typeface tf;

    public AddContactAdapter(Context context, int layout, ArrayList<String> data, String FONT) {
        super(context, layout, contacts);
        this.context = context;
        this.layout = layout;
        tf = Typeface.createFromAsset(context.getAssets(), FONT);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(layout, parent, false);

        TextView suggestion = (TextView) rowView.findViewById(R.id.text1);
        suggestion.setText(getItem(position).toString());
        suggestion.setTypeface(tf);

        return rowView;
    }

然后像这样在 Activity 中分配您的自定义适配器:

CustomAdapter adapter = new CustomAdapter(this, android.R.layout.simple_dropdown_item_1line, data, "path to font");

【讨论】:

  • 我可以把这些代码放在哪里?我可以把它放在片段类中吗?
【解决方案2】:

仔细检查Typewriter.ttf 是您字体的正确文件名,并且它已添加到assets 文件夹中。

编辑

您也可以尝试将TextView id 更改为

android:id="@+id/text1"

并获得视图

TextView scroll = (TextView) findViewById(R.id.text1);

【讨论】:

  • 没问题,我已经在我的应用程序的其他地方使用了相同的字体,并且没有问题。我只是不知道在这种情况下如何使用它!
  • 我做到了,代码没有错误,但在同一行执行时仍然是 NPE!
  • 只是为了确保、调试和评估 scroll 和 type 变量。让我们看看哪个是空的。
  • type 不为空,我在后续代码中使用 setTypeface 命令更改按钮和 textview 的字体,这没有问题。
  • 嗯,我的子弹用完了...您确定为该活动的内容视图设置了正确的布局 xml 吗?
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
相关资源
最近更新 更多