Установите шрифт для элементов списка в Android

Мне нужно добавить собственный шрифт для элементов списка. И я добавил значения в список, используя адаптер, подобный этому

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), newList, R.layout.club_list2, from, to);

Здесь я хочу установить шрифт для текстовых представлений в макете club_list2. Как это возможно?


person Nivedha S    schedule 28.03.2015    source источник


Ответы (3)


Если вы хотите установить свой собственный шрифт из xml, вы можете сделать это

public class TypefaceTextView extends TextView {

    private static Map<String, Typeface> mTypefaces;

    public TypefaceTextView(final Context context) {
        this(context, null);
    }

    public TypefaceTextView(final Context context, final AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        if (mTypefaces == null) {
            mTypefaces = new HashMap<String, Typeface>();
        }

        // prevent exception in Android Studio / ADT interface builder
        if (this.isInEditMode()) {
            return;
        }

        final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
        if (array != null) {
            final String typefaceAssetPath = array.getString(
                    R.styleable.TypefaceTextView_customTypeface);

            if (typefaceAssetPath != null) {
                Typeface typeface = null;

                if (mTypefaces.containsKey(typefaceAssetPath)) {
                    typeface = mTypefaces.get(typefaceAssetPath);
                } else {
                    AssetManager assets = context.getAssets();
                    typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
                    mTypefaces.put(typefaceAssetPath, typeface);
                }

                setTypeface(typeface);
            }
            array.recycle();
        }
    }

}

в xml.

<com.example.TypefaceTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="30sp"
        android:text="@string/hello_world"
        geekui:customTypeface="fonts/yourfont.ttf" />

и ваш шрифт должен быть в папке assets/fonts/

создайте файл ресурсов внутри значений и установите его как имя attrs.xml

затем скопируйте сюда это

<resources>

    <declare-styleable name="TypefaceTextView">
        <attr name="customTypeface" format="string" />
    </declare-styleable>

</resources>
person fish40    schedule 28.03.2015
comment
Я получаю сообщение об ошибке logcat TypefaceTextView не может быть разрешен или не является полем - person Nivedha S; 28.03.2015
comment
com.example.TypefaceTextView — пример пути. убедитесь, что вы указали правильный путь, т.е. com.‹имя вашего пакета›.. - person fish40; 28.03.2015
comment
styleable.TypefaceTextView показывает мне ошибку, и я импортировал свой проект R.styable - person Nivedha S; 28.03.2015
comment
Постарайтесь сделать как можно больше в файлах макета xml, потому что расширение макета намного быстрее, чем выполнение исходного кода. Так что это хорошее решение! Хорошая работа @fish40 - person Mann; 28.03.2015
comment
Отлично, примите как лучший ответ, пожалуйста, это может помочь и другим. - person fish40; 28.03.2015

Если вы хотите, чтобы все они использовали один и тот же, используйте android:typeface в xml. Если вы хотите, чтобы они использовали разные, установите его в TextView в вашей функции getView.

person Gabe Sechan    schedule 28.03.2015
comment
как добавить свой шрифт в xml? - person Nivedha S; 28.03.2015
comment
Если это нестандартно, может быть проще сделать это в коде, особенно при загрузке из активов. Сделайте это в getView адаптера. - person Gabe Sechan; 28.03.2015

по умолчанию не Arial. По умолчанию используется Droid Sans.

переключиться на другой встроенный шрифт

Во-вторых, чтобы перейти на другой встроенный шрифт, используйте android:typeface в разметке XML или setTypeface() в Java (android).

Пример

Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/Arial.otf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf)
person Ram    schedule 28.03.2015