且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 中更改全息主题的菜单项文本颜色?

更新时间:2023-12-04 22:11:52

我通过检查设备版本通过菜单代码更改背景颜色来解决.

I have solved by changing the background color by code of menu by checking the device version.

如果设备不支持溢出菜单,您可以更改菜单的背景颜色,也可以使用以下方法更改菜单文本颜色:

If device doen't support overflow menu, the, you can change the background color of menu as well as you can also change menu text color using following one:

static final Class<?>[] constructorSignature = new Class[] {Context.class, AttributeSet.class};

class MenuColorFix implements LayoutInflater.Factory {
public View onCreateView(String name, Context context, AttributeSet attrs) {
    if (name.equalsIgnoreCase("com.android.internal.view.menu.ListMenuItemView")) {
        try {
            Class<? extends ViewGroup> clazz = context.getClassLoader().loadClass(name).asSubclass(ViewGroup.class);
            Constructor<? extends ViewGroup> constructor = clazz.getConstructor(constructorSignature);
            final ViewGroup view = constructor.newInstance(new Object[]{context,attrs});

            new Handler().post(new Runnable() {
                public void run() {
                    try {
                        view.setBackgroundColor(Color.GRAY);
                        List<View> children = getAllChildren(view);
                        for(int i = 0; i< children.size(); i++) {
                            View child = children.get(i);
                            if ( child instanceof TextView ) {
                                ((TextView)child).setTextColor(Color.BLACK);
                            }
                        }
                    }
                    catch (Exception e) {
                        Log.i(TAG, "Caught Exception!",e);
                    }

                }
            });
            return view;
        }
        catch (Exception e) {
            Log.i(TAG, "Caught Exception!",e);
        }
    }
    return null;
}       
}

public List<View> getAllChildren(ViewGroup vg) {
ArrayList<View> result = new ArrayList<View>();
for ( int i = 0; i < vg.getChildCount(); i++ ) {
    View child = vg.getChildAt(i);
    if ( child instanceof ViewGroup) {
        result.addAll(getAllChildren((ViewGroup)child));
    }
    else {
        result.add(child);
    }
}
return result;
}

//并在onCreateContextMenu中,放置如下代码

//and in onCreateContextMenu, placed following code

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
LayoutInflater lInflater = getLayoutInflater();
if ( lInflater.getFactory() == null ) {
    lInflater.setFactory(new MenuColorFix());
}
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.myMenu, menu);
}