Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

android - Different look/style for specific menu item on ActionBar

On my Android application I am customizing the ActionBar following tips from the android developer blog and other places. I would like to be able to highlight a specific menu item on the ActionBar e.g. with a different background color because it is especially applicable to a currently visible fragment (which actually added it). However I have not found any indication that this can be done nor have I managed to do so myself yet. Is it possible? If so how?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So I got this to work now with a bit of a trick to it. Here goes the fragment code

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    menuItemCreateCart = menu.findItem(R.id.menuItemCreateCart);
    if (menuItemCreateCart  == null) {
        menuItemCreateCart  = menu.add(0, R.id.menuItemCreateCart, 0, R.string.Create);
    }

    TextView tv = new TextView(getActivity());
    tv.setText(R.string.Create);
    tv.setTextColor(getResources().getColor(R.color.green));
    tv.setBackgroundColor(getResources().getColor(R.color.lightBlue));
    tv.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    createCart();
                }
            }
    );
    menuItemCreateCart.setActionView(tv);

The main gotcha is that the onclicklistener has to be set on the view that you set as action view and not the menu item for it to work. This way you can do whatever you like.

Also note that you can NOT use getActionView to retrieve the originally set view with title because it will return null. It seem to be more of an alternative view than the actual view for default menu items..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...