gpt4 book ai didi

android - 我如何在 fragment 布局中使用自定义字体?

转载 作者:行者123 更新时间:2023-11-29 14:47:10 25 4
gpt4 key购买 nike

*编辑

我认为它必须与 Android 5.0.2 相关。我尝试了一个 Activity ,它给了我同样的错误。

所以我是抽屉导航和 fragment 的新手。一切正常,现在我想要一个带有自定义字体的 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 编程的新手,我真的想要一个解决方案并想了解为什么它是错误的。非常感谢所有帮助!

最佳答案

你只需要改变一些东西。您需要先膨胀 View ,然后再获取其子项,并获取获取 Assets 的 Activity :

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;


}
}

关于android - 我如何在 fragment 布局中使用自定义字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31569884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com