9

我有相同的标准选项菜单,但我想将项目的背景从白色更改为黑色。我看过很多关于如何做到这一点的帖子,但这些帖子不适用于 2.3。

有谁知道具有与 2.3 版兼容的自定义颜色背景的工作菜单充气机?

**注意* * 没有图像放置!!!没有其他帖子的代码,因为我在这里都试过了!!!

4

6 回答 6

8

看看以下解决方案是否能解决您的问题......

AndroidMenifest.xml

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/CustomTheme">

菜单/选项.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/option_1" android:title="Android"/>
    <item android:id="@+id/option_2" android:title="iPhone"/>
    <item android:id="@+id/option_3" android:title="iPad"/>
</menu>

样式.xml

<resources>
    <style name="CustomTheme" parent="android:Theme">
        <!-- Panel attributes -->
        <!-- <item name="android:panelBackground">@drawable/menu_bg</item> -->
        <item name="android:panelFullBackground">@drawable/menu_full_bg</item> 
            <!--    <item name="android:panelColorBackground">#FF0000</item> -->
    </style>

    <!-- <drawable name="menu_bg">#DDDAAA</drawable> -->
    <drawable name="menu_full_bg">#000FFF</drawable>

</resources>

StackoverflowActivity.java

public class StackoverflowActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options, menu);
        return true;
    }

}

输出

于 2012-05-11T13:54:59.573 回答
7

下面的代码工作正常 2.3.6(在设备和模拟器上测试)。它几乎是从谷歌搜索的不同网站复制和组合的

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    setMenuBackground();
    return super.onCreateOptionsMenu(menu);
}

protected void setMenuBackground() {
    getLayoutInflater().setFactory(new Factory() {
     @Override
                public View onCreateView(final String name, final Context context,
                        final AttributeSet attrs) {

                    if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {

                        try { // Ask our inflater to create the view
                            final LayoutInflater f = getLayoutInflater();
                            final View[] view = new View[1];
                            try {
                                view[0] = f.createView(name, null, attrs);
                            } catch (InflateException e) {
                                hackAndroid23(name, attrs, f, view);
                            }
                            // Kind of apply our own background
                            new Handler().post(new Runnable() {
                                public void run() {
                                    view[0].setBackgroundColor(Color.BLUE);

                                }
                            });
                            return view[0];
                        } catch (InflateException e) {
                        } catch (ClassNotFoundException e) {

                        }
                    }
                    return null;
                }
            });
        }

        static void hackAndroid23(final String name,
                final android.util.AttributeSet attrs, final LayoutInflater f,
                final View[] view) {
            try {
                f.inflate(new XmlPullParser() {
                    @Override
                    public int next() throws XmlPullParserException, IOException {
                        try {
                            view[0] = (TextView) f.createView(name, null, attrs);
                        } catch (InflateException e) {
                        } catch (ClassNotFoundException e) {
                        }
                        throw new XmlPullParserException("exit");
                    }

                    @Override
                    public void defineEntityReplacementText(String entityName,
                            String replacementText)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public int getAttributeCount() {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public String getAttributeName(int index) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getAttributeNamespace(int index) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getAttributePrefix(int index) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getAttributeType(int index) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getAttributeValue(int index) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getAttributeValue(String namespace,
                            String name) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public int getColumnNumber() {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public int getDepth() {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public int getEventType() throws XmlPullParserException {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public boolean getFeature(String name) {
                        // TODO Auto-generated method stub
                        return false;
                    }

                    @Override
                    public String getInputEncoding() {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public int getLineNumber() {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public String getName() {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getNamespace() {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getNamespace(String prefix) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public int getNamespaceCount(int depth)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public String getNamespacePrefix(int pos)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getNamespaceUri(int pos)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getPositionDescription() {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getPrefix() {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public Object getProperty(String name) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public String getText() {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public char[] getTextCharacters(
                            int[] holderForStartAndLength) {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public boolean isAttributeDefault(int index) {
                        // TODO Auto-generated method stub
                        return false;
                    }

                    @Override
                    public boolean isEmptyElementTag()
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub
                        return false;
                    }

                    @Override
                    public boolean isWhitespace() throws XmlPullParserException {
                        // TODO Auto-generated method stub
                        return false;
                    }

                    @Override
                    public int nextTag() throws XmlPullParserException,
                            IOException {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public String nextText() throws XmlPullParserException,
                            IOException {
                        // TODO Auto-generated method stub
                        return null;
                    }

                    @Override
                    public int nextToken() throws XmlPullParserException,
                            IOException {
                        // TODO Auto-generated method stub
                        return 0;
                    }

                    @Override
                    public void require(int type, String namespace, String name)
                            throws XmlPullParserException, IOException {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void setFeature(String name, boolean state)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void setInput(Reader in)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void setInput(InputStream inputStream,
                            String inputEncoding) throws XmlPullParserException {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void setProperty(String name, Object value)
                            throws XmlPullParserException {
                        // TODO Auto-generated method stub

                    }
                }, null, false);
            } catch (InflateException e1) {
                // "exit" ignored
            }
        }
于 2012-05-05T04:05:28.227 回答
5

在理想情况下,您不应该这样做。根据他们的决定,各种设备会有不同的颜色。如果您真的必须自定义菜单项的背景,那么,我建议不要使用它。相反,创建某种上下文菜单,您可以根据需要对其进行完全自定义。

我知道它可能不是您要求的解决方案,但是无论您为此采取什么解决方法,它都可能适用于一些设备,并且可能对其他人来说是一场灾难。

于 2012-05-11T04:17:48.343 回答
4

我正在寻找相同的东西,但是当我将我的应用程序安装在版本为 2.3.6的三星 Galaxy Y中时。我自动获得了选项菜单的黑色背景。虽然模拟器为我显示相同菜单的白色背景。我不知道它是如何工作的,但我得到了我想要的。所以我没有改变它。 这是代码:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflater1 = getMenuInflater();
    inflater1.inflate(R.menu.scfmenu, menu);

    return true;
}



@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.settings:
        Intent i = new Intent(getApplicationContext(), prefsActivity.class);
        startActivity(i);
        break;
    case R.id.logout:
        Intent j = new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(j);
        break;
    }

    return super.onOptionsItemSelected(item);
}
于 2012-05-01T06:05:44.213 回答
2

我在 2.3.1 版本上使用了如下所示的代码,它可以工作,只需调用 onCreat 方法 addOptionsMenuHackerInflaterFactory();

private static final int COLOR_MENU_ID = Menu.FIRST;
private static final int EMBOSS_MENU_ID = Menu.FIRST + 1;
private static final int BLUR_MENU_ID = Menu.FIRST + 2;


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
    menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's');
    menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z');
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}
@SuppressWarnings("rawtypes")
static Class       IconMenuItemView_class = null;
@SuppressWarnings("rawtypes")
static Constructor IconMenuItemView_constructor = null;

// standard signature of constructor expected by inflater of all View classes
@SuppressWarnings("rawtypes")
private static final Class[] standard_inflater_constructor_signature = 
new Class[] { Context.class, AttributeSet.class };

protected void addOptionsMenuHackerInflaterFactory()
{
    final LayoutInflater infl = getLayoutInflater();

    infl.setFactory(new Factory()
    {
        public View onCreateView(final String name, 
                                 final Context context,
                                 final AttributeSet attrs)
        {
            if (!name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView"))
                return null; // use normal inflater

            View view = null;

            // "com.android.internal.view.menu.IconMenuItemView" 
            // - is the name of an internal Java class 
            //   - that exists in Android <= 3.2 and possibly beyond
            //   - that may or may not exist in other Android revs
            // - is the class whose instance we want to modify to set background etc.
            // - is the class we want to instantiate with the standard constructor:
            //     IconMenuItemView(context, attrs)
            // - this is what the LayoutInflater does if we return null
            // - unfortunately we cannot just call:
            //     infl.createView(name, null, attrs);
            //   here because on Android 3.2 (and possibly later):
            //   1. createView() can only be called inside inflate(),
            //      because inflate() sets the context parameter ultimately
            //      passed to the IconMenuItemView constructor's first arg,
            //      storing it in a LayoutInflater instance variable.
            //   2. we are inside inflate(),
            //   3. BUT from a different instance of LayoutInflater (not infl)
            //   4. there is no way to get access to the actual instance being used
            // - so we must do what createView() would have done for us
            //
            if (IconMenuItemView_class == null)
            {
                try
                {
                    IconMenuItemView_class = getClassLoader().loadClass(name);
                }
                catch (ClassNotFoundException e)
                {
                    // this OS does not have IconMenuItemView - fail gracefully
                    return null; // hack failed: use normal inflater
                }
            }
            if (IconMenuItemView_class == null)
                return null; // hack failed: use normal inflater

            if (IconMenuItemView_constructor == null)
            {
                try
                {
                    IconMenuItemView_constructor = 
                    IconMenuItemView_class.getConstructor(standard_inflater_constructor_signature);
                }
                catch (SecurityException e)
                {
                    return null; // hack failed: use normal inflater
                }
                catch (NoSuchMethodException e)
                {
                    return null; // hack failed: use normal inflater
                }
            }
            if (IconMenuItemView_constructor == null)
                return null; // hack failed: use normal inflater

            try
            {
                Object[] args = new Object[] { context, attrs };
                view = (View)(IconMenuItemView_constructor.newInstance(args));
            }
            catch (IllegalArgumentException e)
            {
                return null; // hack failed: use normal inflater
            }
            catch (InstantiationException e)
            {
                return null; // hack failed: use normal inflater
            }
            catch (IllegalAccessException e)
            {
                return null; // hack failed: use normal inflater
            }
            catch (InvocationTargetException e)
            {
                return null; // hack failed: use normal inflater
            }
            if (null == view) // in theory handled above, but be safe... 
                return null; // hack failed: use normal inflater


            // apply our own View settings after we get back to runloop
            // - android will overwrite almost any setting we make now
            final View v = view;
            new Handler().post(new Runnable()
            {
                public void run()
                {
                    v.setBackgroundColor(Color.BLUE);

                    try
                    {
                        // in Android <= 3.2, IconMenuItemView implemented with TextView
                        // guard against possible future change in implementation
                        TextView tv = (TextView)v;
                        tv.setTextColor(Color.RED);
                    }
                    catch (ClassCastException e)
                    {
                        // hack failed: do not set TextView attributes
                    }
                }
            });

            return view;
        }
    });
}

背景蓝色和文本颜色红色的输出如下所示 在此处输入图像描述

于 2012-05-12T05:34:15.237 回答
2

我从 codeproject发现了这篇有趣的帖子。您可以自定义您想要的一切:bk 颜色、图标。您可以使用以下方法更改菜单样式:

  mMenu.setItemsPerLineInLandscapeOrientation(8);
  mMenu.setItemsPerLineInPortraitOrientation(4);

注意:添加类似于选项菜单的视图是一个技巧。希望这有帮助!

于 2012-05-04T08:29:35.487 回答