如何在AutocompleteTextview的建议中更改字体?

时间:2013-10-05 14:58:15

标签: android fonts android-arrayadapter autocompletetextview typeface

我正在尝试更改通过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。有人知道如何继续吗?

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

仔细检查Typewriter.ttf是否为您的字体的正确文件名,并将其添加到assets文件夹。

修改

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

android:id="@+id/text1"

并使用

获取视图
TextView scroll = (TextView) findViewById(R.id.text1);