2016-06-14 11 views
0

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

@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, но попытки изменить шрифт для нескольких TextViews как в код выше, я получаю ошибку 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 и андроид программирования. Помогите мне найти решение при изменении всех текстовых элементов в фрагменте с помощью специального шрифта. Заранее спасибо !!

+2

убедитесь, что указанные вами тексты в вашем макете. – Neji

+0

поделитесь своим 'fragment_interest.xml' .. !! –

+0

убедитесь, что у вас есть textview с id textview1 и textview2 в вашем макете fragment_interest.xml –

ответ

0

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

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

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

0

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

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

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

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

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

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

Оберните Context активность:

@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"/> 
0

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

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); 
     } 
    } 

} 
0

Попробуйте искать все 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")); 
}