改变字体不会对片段起作用

时间:2014-01-26 18:05:28

标签: android android-fragments

似乎我无法在我的应用上更改字体。我已将我的字体粘贴在ASSETS> FONTS上,但现在仍然运气..

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_menu2, container, false);
    TextView txt = (TextView) v.findViewById(R.id.kernel);
      Typeface font = Typeface.createFromAsset(getActivity().getAssets(),    "EVERAFTE.TTF");
      txt.setTypeface(font); 
    return v;

XML文件

    <TextView
    android:id="@+id/kernel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Kernel"
    android:textAppearance="?android:attr/textAppearanceLarge" />

2 个答案:

答案 0 :(得分:0)

Typeface font = Typeface.createFromAsset(getActivity()。getAssets(),“FONTS / EVERAFTE.TTF”);

答案 1 :(得分:0)

第一

你不应该在onCreateView方法中设置类型面,你需要在创建视图后这样做。

请参阅:

TextView txt;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState){
        View v = inflater.inflate(R.layout.fragment_menu2, container, false);
        txt = (TextView) v.findViewById(R.id.kernel);
        return v;


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(),    "FONTS/EVERAFTE.TTF");
      txt.setTypeface(font); 
        super.onViewCreated(view, savedInstanceState);
    }

并确保字体路径为true。 (区分大小写。)


编辑:

创建自定义TextView并在布局中使用它:

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.widget.TextView;

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 font = Typeface.createFromAsset(getContext().getAssets(),    "FONTS/EVERAFTE.TTF");
                 setTypeface(font );
        }
    }

}

然后在xml文件中:

 <yourpackagename.MyTextView 
    android:id="@+id/kernel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Kernel"
    android:textAppearance="?android:attr/textAppearanceLarge" />