Android偏好活动字体预览

时间:2016-01-12 06:18:00

标签: android android-preferences preferenceactivity listpreference

我创建了android偏好活动,以这种方式更改字体

Android偏好设置活动正常但我想在ListPreference中显示字体预览

像这样 font changing

public class SettingsActivity extends AppCompatPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();


}


/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Show the Up button in the action bar.
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        if (!super.onMenuItemSelected(featureId, item)) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return true;
    }
    return super.onMenuItemSelected(featureId, item);
}


/**
 * {@inheritDoc}
 */
@Override
public boolean onIsMultiPane() {
    return isXLargeTablet(this);
}

/**
 * Helper method to determine if the device has an extra-large screen. For
 * example, 10" tablets are extra-large.
 */
private static boolean isXLargeTablet(Context context) {
    return (context.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}

/**
 * {@inheritDoc}
 */
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.pref_headers, target);
}

/**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.
 */
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener =
        new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {

                        }
                    }

        };


private static void bindPreferenceSummaryToValue(Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    ............................;
}

/**
 * This method stops fragment injection in malicious applications.
 * Make sure to deny any unknown fragments here.
 */
protected boolean isValidFragment(String fragmentName) {
    return PreferenceFragment.class.getName().equals(fragmentName)
    || fontPreferenceFragment.class.getName().equals(fragmentName);
}


//    Font   PreferenceFragment
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class fontPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_font);
        setHasOptionsMenu(true);


        bindPreferenceSummaryToValue(findPreference("font"));
        bindPreferenceSummaryToValue(findPreference("fontsizes"));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            startActivity(new Intent(getActivity(), SettingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

  }

和R.xml.pref_font是

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
   <ListPreference
    android:defaultValue="1"
    android:entries="@array/pref_font_list_titles"
    android:entryValues="@array/pref_font_list_titles_values"
    android:key="font"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/pref_font_title_header"/>

   <ListPreference

    android:defaultValue="1"
    android:entries="@array/pref_font_size_titles"
    android:entryValues="@array/pref_font_size_titles_values"
    android:key="fontsizes"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="Font size"

    />

1 个答案:

答案 0 :(得分:1)

经过长时间的搜索,我想出了如何做到这一点

enter image description here

设置页面XML文件

<com.........ArabicFontNameListPreference
        android:defaultValue="1"
        android:entries="@array/pref_font_list_titles_ar"
        android:entryValues="@array/pref_font_list_titles_values_ar"
        android:key="font_ar"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        android:title="@string/pref_font_title_ar"
        android:summary="@string/pref_font_title_ar_summary">

    </com.........ArabicFontNameListPreference>

和ArabicFontNameListPreference.java

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.preference.ListPreference;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;



/**
  * Created by Basil on 04-03-2016.
  */
public class ArabicFontNameListPreference extends ListPreference {
private int mClickedDialogEntryIndex;

public ArabicFontNameListPreference(Context context) {
    super(context);
}

public ArabicFontNameListPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
}


@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    if (getEntries() == null || getEntryValues() == null) {
        super.onPrepareDialogBuilder(builder);
        return;
    }


    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), R.layout.preference_ar_font_name, getEntries()) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            float fontSizePx = getContext().getResources().getDimension(R.dimen.def_font_size_list_pref);
            Typeface tf = null;
            CheckedTextView view = (CheckedTextView) convertView;
            if (view == null) {
                view = (CheckedTextView) View.inflate(getContext(), R.layout.preference_ar_font_name, null);
            }
            switch (position) {
                case 0:
//                      fontSizePx =       getContext().getResources().getDimension(R.dimen.font_size_small_small);
                    tf =      Typeface.createFromAsset(getContext().getAssets(), "fonts/RobotoRegular.ttf");
                    break;
                case 1:
                    tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/RobotoRegular.ttf");
 //                     fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_medium_medium);
                    break;
//                    case 2:
//                        tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/MADDINA.ttf");
////                        fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_small_medium);
//                        break;
//                    case 3:
//                        tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/trado.ttf");
 //                        break;
//                    case 4:
  //                        tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/ScheherazadeRegOT.ttf");
//                        break;
//                    case 5:
//                        tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Symbols1_Ver02 (1).otf");
//                        break;
//                    case 6:
//                        tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/UthmanTN1 Ver10.otf");
//                        break;
                default:

            }
            view.setText(getEntries()[position]);
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx);
            view.setTypeface(tf, Typeface.BOLD);
            return view;
        }
    };

    mClickedDialogEntryIndex = findIndexOfValue(getValue());
    builder.setSingleChoiceItems(adapter, mClickedDialogEntryIndex, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            mClickedDialogEntryIndex = which;
            ArabicFontNameListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
            dialog.dismiss();
        }
    });
    builder.setPositiveButton(null, null);


}

@Override
protected void onDialogClosed(boolean positiveResult) {
    super.onDialogClosed(positiveResult);

    if (positiveResult && mClickedDialogEntryIndex >= 0 && getEntryValues() != null) {
        String val = getEntryValues()[mClickedDialogEntryIndex].toString();
        if (callChangeListener(val)) {
            setValue(val);
        }
    }
 }
}

和preference_ar_font_name.xml为

 <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeightSmall"
    android:height="48dp"
    android:checkMark="@null"
    android:drawableLeft="?android:attr/listChoiceIndicatorSingle"
    android:drawableStart="?android:attr/listChoiceIndicatorSingle"
    android:gravity="center_vertical"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
    android:paddingRight="?android:attr/listPreferredItemPaddingRight"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:textAppearance="?android:attr/textAppearanceListItemSmall" />