【问题标题】:Set custom font for Android fragments为 Android 片段设置自定义字体
【发布时间】:2012-08-21 20:11:11
【问题描述】:

我一直在使用Jake Wharton's ViewPagerIndicator,目前我正在尝试在我的一个片段上实现自定义字体。我试过使用这段代码:

   TextView txt = (TextView) findViewById(R.id.Zipcode);
    Typeface font = Typeface.createFromAsset(getAssets(), "fonts/customfont.ttf");
    txt.setTypeface(font); 

在主要活动的onCreate 中导致logcat 中出现空指针异常,偶尔typeface cannot be made。我还尝试在onCreate 和onCreateView 中设置片段本身的字体,但是findViewById 和getAssests() 是片段范围内的未知方法。

我无法确定字体是问题还是我尝试设置字体的位置是问题。

【问题讨论】:

  • customfont.ttf 在 assets/fonts/ 中吗?
  • @kcoppock 正确我在资产/字体中有它

标签: android fonts android-fragments


【解决方案1】:

你可以试试这个

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle     savedInstanceState) {
       View v = inflater.inflate(R.layout.fragment_layout, container, false);
       TextView txt = (TextView) v.findViewById(R.id.Zipcode);
       Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/customfont.ttf");
       txt.setTypeface(font); 
       return v;
}

有了这个,你可以在片段范围内获得上下文并获取视图和资产

【讨论】:

  • 这行得通。此外,onCreateView 必须返回您的代码没有的视图。 return v; 应该在底部。
  • 由于某种原因我的应用是 FC :/
【解决方案2】:

在 yourViewHolder 类中定义字体`

Typeface customFontBold= Typeface.createFromAsset(getActivity().getAssets(),"fonts/JosefinSans-Bold.ttf");

像这样。

【讨论】:

    【解决方案3】:

    我的简单代码是更改方法调用“上下文” 带有“getContext(); //getContext和getActvity在fragment中是一样的吗??

    **result**.setText("Value Expenses = " +expenses);
    Typeface supercell = Typeface.createFromAsset(**getContext()**.getAssets(), "fonts/Supercell.ttf");**
    **result.setTypeface(supercell);**
    }catch (Exception e) 
    {
    Toast.makeText(getActivity(), "SUCCEED, VALUES RESULT", Toast.LENGTH_SHORT)
    .show();
    }
    break;
    

    【讨论】:

      猜你喜欢
      • 2022-12-23
      • 2012-02-27
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 2020-04-21
      相关资源
      最近更新 更多