如何在片段布局中使用自定义字体?

时间:2015-07-22 17:18:49

标签: android android-fragments custom-font

*编辑

我认为它必须与Android 5.0.2做点什么。我尝试了一个活动,它给了我同样的错误。

所以我是导航抽屉和碎片的新手。一切正常,现在我想要一个自定义字体的textview。通常它适用于下面的方法,但现在它没有。

public class HomeFragment extends Fragment {

public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // I use this everytime for normal layouts, but with a fragment layout it doesnt work
    TextView txt = (TextView) findViewById(R.id.textViewHome);  
    Typeface font = Typeface.createFromAsset(getAssets(), "impact.ttf");  
    txt.setTypeface(font); 



    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    return rootView;


}
}

我得到的错误是:

The method getAssets() is undefined for the type HomeFragment
The method findViewById(int) is undefined for the type HomeFragment 

由于我是Android编程的新手,我真的想要一个解决方案,并希望了解它为什么是错误的。所有帮助都非常感谢!

3 个答案:

答案 0 :(得分:6)

你只需要改变一些事情。您需要先获取视图,然后再获取其子项,并获取活动以获取资产:

public class HomeFragment extends Fragment {

  public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    TextView txt = (TextView) rootView.findViewById(R.id.textViewHome);  
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "impact.ttf");  
    txt.setTypeface(font); 

    return rootView;


}
}

答案 1 :(得分:0)

只需进行此更改即可。

 public class HomeFragment extends Fragment {
 public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {


TextView txt = (TextView) findViewById(R.id.textViewHome);  
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "impact.ttf");  
txt.setTypeface(font); 



View rootView = inflater.inflate(R.layout.fragment_home, container, false);

return rootView;
 }
                                         }

这里getActivity()将为您提供上下文,您可以从此上下文访问assets文件夹。它会起作用:))

答案 2 :(得分:0)

尝试将s添加到字体,例如assets / fonts