gpt4 book ai didi

android - 如何更改 PopupMenu 项目的字体

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:01:02 26 4
gpt4 key购买 nike

我想更改 PopupMenu 项的默认字体,并为它们使用我的自定义字体。

这是我用来创建 PopupMenu 的代码:

PopupMenu pm = new PopupMenu(this, v);
getMenuInflater().inflate(R.menu.main, pm.getMenu());
pm.show();

和菜单项:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Setting"
android:title="Setting"/>
<item
android:id="@+id/About"
android:title="About"/>
<item
android:id="@+id/Help"
android:title="Help"/>
</menu>

如果您能与我分享您的建议,我将非常感激:-)

问候

最佳答案

检查我的相同问题的解决方案:

弹出菜单方法:

 private void showEditPopupWindow(Context mContext) {
PopupMenu popupMenu = new PopupMenu(mContext, view);
popupMenu.getMenuInflater().inflate(R.menu.YOUR_MENU, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.delete) {
// Do your stuffs;
} else {
// Do your stuffs
}
return true;
}
});

Menu menu = popupMenu.getMenu();
for (int i = 0; i < menu.size(); i++) {
MenuItem mi = menu.getItem(i);
applyFontToMenuItem(mi);
}

}

在这个方法中应用你的字体,你也可以改变字体的颜色:

private void applyFontToMenuItem(MenuItem mi) {
Typeface font = Typeface.createFromAsset(mContext.getAssets(), "fonts/YOUR_FONT.ttf");
SpannableString mNewTitle = new SpannableString(mi.getTitle());
mNewTitle.setSpan(new CustomTypeFaceSpan("", font,Color.WHITE), 0, mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mi.setTitle(mNewTitle);
}

CustomTypeFaceSpan 类:

    public class CustomTypeFaceSpan extends TypefaceSpan {

private final Typeface newType;
private final int mColor;

public CustomTypeFaceSpan(String family, Typeface type, @ColorInt int color) {

super(family);
newType = type;
mColor = color;
}

@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(mColor);
applyCustomTypeFace(ds, newType);
}

@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}

@Override
public int getSpanTypeId() {
return super.getSpanTypeId();
}

@ColorInt
public int getForegroundColor() {
return mColor;
}




private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}

int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}

if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}

paint.setTypeface(tf);
}
}

关于android - 如何更改 PopupMenu 项目的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26957925/

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