0

我有一个扩展FragmentActivity的类,在我创建的Fragment里面只有一个textView。动态地改变textview中的片段

我想放在动作条(已完成),可以使这个TextView的用户改变字体类型的设置按钮。

我怎么能实现这个?

我还有一个问题,那就是FragmentActivity中片段的数量并不为先验知... 所以当我改变我的字体类型时,我想改变每一个片段。

我试图把一个方法changefont我的片段里面,但我不知道我怎么会管理..

public void setFont(){ 
      TextView textView = (TextView) getView().findViewById(R.id.detailsText); 
      textView.setTypeface(); 
//Another problem how set typeface, because 
//Typeface font = Typeface.createFromAsset(getAssets(),"fonts/font.tff"); couldn't work because I'm inside a Fragment and getAssets() just rise errors.. 
     } 

我很卡..难道你们能帮我吗?

回答

0

使一类的东西叫做Utils.java并把这个方法: -

public static void setFontSignika_Bold(TextView textView) { 
      Typeface tf = Typeface.createFromAsset(textView.getContext() 
        .getAssets(), "fonts/signikabold.ttf"); 

      textView.setTypeface(tf); 

     } 

现在,你可以通过这种方式在整个应用程序使用此: -

Utils.setFontSignika_Bold(textView); // Pass your textview object 
+0

我有一个NullPointerExeption,因为我想获得一个TextView从动作条片段内。所以当我调用这个方法时,我使用参数((TextView)findViewById(R.id.text));但当然这会引发异常 –

0

您也可以创建TextView的子类并在里面设置字体。 Context对象包含getAssets()方法:)

例实施扩展文本视图:

public class TextViewPlus extends TextView { 
    private static final String TAG = "TextView"; 

    public TextViewPlus(Context context) { 
     super(context); 
    } 

    public TextViewPlus(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setCustomFont(context, attrs); 
    } 

    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     setCustomFont(context, attrs); 
    } 

    private void setCustomFont(Context ctx, AttributeSet attrs) { 
     TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus); 
     String customFont = a.getString(R.styleable.TextViewPlus_customFont); 
     setCustomFont(ctx, customFont); 
     a.recycle(); 
    } 

    public boolean setCustomFont(Context ctx, String asset) { 
     Typeface tf = null; 
     try { 
     tf = Typeface.createFromAsset(ctx.getAssets(), asset); 
     } catch (Exception e) { 
      Log.e(TAG, "Could not get typeface: "+e.getMessage()); 
      return false; 
     } 

     setTypeface(tf); 
    setPaintFlags(getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG | Paint.DEV_KERN_TEXT_FLAG); 
     return true; 
    } 

} 
+0

不是我的第一个问题,我必须从ActionBar访问Fragment中的TextView:/ –