Как применить собственный шрифт к нескольким TextView внутри фрагмента?

Я пытаюсь изменить шрифт по умолчанию для нескольких TextViews в фрагменте Android с помощью пользовательского шрифта. Код для этого находится в onCreateView фрагмента, как показано ниже:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_interest, container, false);
    TextView txt1 = (TextView)v.findViewById(R.id.textView1);
    TextView txt2 = (TextView)v.findViewById(R.id.textView2);
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HoneyScript-SemiBold.ttf");

    txt1.setTypeface(font);
    txt2.setTypeface(font);

    return v;

}

Код работает, если я меняю шрифт только для одного TextView, но при попытке изменить шрифт для нескольких TextView, как в приведенном выше коде, я получаю ошибку NullPointerException:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
                                                                                     at layout.InterestFragment.onCreateView(InterestFragment.java:81)
                                                                                     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                                                                                     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                                     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                                                                                     at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
                                                                                     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
                                                                                     at com.android.niraj.financialcalculator.MainActivity.onStart(MainActivity.java:221)
                                                                                     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
                                                                                     at android.app.Activity.performStart(Activity.java:6253)
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                     at android.os.Looper.loop(Looper.java:148) 
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Я новичок в программировании на Java и Android. Пожалуйста, помогите мне найти решение по изменению всех TextViews во фрагменте с помощью пользовательского шрифта. Заранее спасибо !!


person Niraj73    schedule 14.06.2016    source источник
comment
убедитесь, что упомянутые вами текстовые представления присутствуют в вашем макете.   -  person Neji    schedule 14.06.2016
comment
поделись своим fragment_interest.xml..!!   -  person Janki Gadhiya    schedule 14.06.2016
comment
убедитесь, что у вас есть текстовое представление с идентификаторами textview1 и textview2 в вашем макете fragment_interest.xml   -  person Vishwesh Jainkuniya    schedule 14.06.2016
comment
убедитесь, что TextView txt1 и txt2 и шрифт Typeface не имеют нулевой ссылки.   -  person Divyesh Boda    schedule 14.06.2016


Ответы (4)


добавить эту строку

textview.setTypeface(GloabalTypeface._globalTypeface(this, "Roboto-Light"));

здесь я использую этот стиль шрифта «Roboto-Light».

person RejoylinLokeshwaran    schedule 14.06.2016

Для этого можно использовать Calligraphy. (Зачем изобретать велосипед, когда что-то уже сделано)

Включить зависимость

dependencies {
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
}

Добавьте свои пользовательские шрифты в активы / все определения шрифтов относятся к этому пути.

Определите шрифт по умолчанию с помощью CalligraphyConfig в классе приложения в методе #onCreate().

@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}

Оберните контекст действия:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

Вы готовы идти!

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fontPath="fonts/Roboto-Bold.ttf"/>
person PsyGik    schedule 14.06.2016

Просто вызовите этот метод, передав родительское представление в качестве аргумента.

private void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
        }
    } catch (Exception e) {
 }
 }

Чтобы применить шрифт для просмотра себя не во время выполнения (лучше всего для производительности)

public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
            setTypeface(tf);
        }
    }

}
person Kumar M    schedule 14.06.2016

Попробуйте найти все TextView в своем View и изменить шрифт для каждого из них:

for( int i = 0; i < mainView.getChildCount(); i++ ){
  if( mainView.getChildAt( i ) instanceof TextView )
    mainView.getChildAt( i ).setTypeface(GloabalTypeface._globalTypeface(this, "Roboto-Light"));
}
person Nicolas Cortell    schedule 14.06.2016