我正在尝试在PreferenceActivity中设置自定义TTF字体。
首选项活动包含2个ListPreferences,没有别的。 在我的PreferenceActivity中,我有这段代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference conPref = findPreference(key);
// this works correctly, i'm able to get the correct text form tv.getText();
TextView tv = (TextView) conPref.getView(null, null).findViewById(android.R.id.title);
Typeface gilFontBook = Typeface.createFromAsset(getAssets(), "fonts/gilbook.ttf");
tv.setTypeface(gilFontBook); // doesnt change the typeface
}
但这不适用于我。在从ListPreference
中选择项目之前和之后,字体保持不变答案 0 :(得分:0)
据我所知,你要扩展PreferenceActivity类来做到这一点。这个答案对我有所帮助:
答案 1 :(得分:0)
我以粗暴的方式做到了:
public class FontPreference extends Preference {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public FontPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public FontPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FontPreference(Context context) {
super(context);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
loopOverViewGroup(view);
}
private void loopOverViewGroup(View view){
if(view instanceof ViewGroup){
ViewGroup group = (ViewGroup)view;
for(int i = 0; i < ((ViewGroup)view).getChildCount(); i++){
View childView = ((ViewGroup)view).getChildAt(i);
if(childView instanceof ViewGroup){
loopOverViewGroup(childView);
}else{
setTypeFace(childView);
}
}
}
}
private void setTypeFace(View view){
if(view instanceof TextView){
((TextView)view).setTypeface(Typeface.createFromAsset(getContext().getAssets(), "YOURFONT.ttf"));
((TextView)view).setTextColor(getContext().getResources().getColor(Color.WHITE));
}
}
}