1

Im trying to change the font of my menu items to a custom font. In my action bar is a dropdown menu with a couple of options. When I pick one the these options, the title of the item in the actionbar changes to this optiontext and it will apply the font. This is because I applied te font in the overrided 'onOptionItemSelected(MenuItem item)'. I really want the font to be applied when the menu gets created (it uses the default font right now). So I attempted to do this in the 'onCreateOptionsMenu(Menu menu)', but it keeps giving me an error (null pointer exception). I even tried multiple overrided methods, but nothing seems to work. How can I get my custom font applied to the menu item when it's been created? Here is my code:

        @Override
        public boolean onCreateOptionsMenu(Menu menu){
            Log.d("GraphActivity", "onCreateOptionsMenu");
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_graph, menu);
            optionMenu = menu;
            Boolean dayMatch = User.getInstance().getDownloadedDay() == User.getInstance().getCurrentDay();
            Boolean monthMatch = User.getInstance().getDownloadedMonth() == User.getInstance().getCurrentMonth();
             Boolean yearMatch = User.getInstance().getDownloadedYear() == User.getInstance().getCurrentYear();
            if(! dayMatch || ! monthMatch || ! yearMatch){
                FeedbackManager feedbackManager = new FeedbackManager();
                feedbackManager.showToast("file is out of date", GraphActivity.this, Toast.LENGTH_SHORT);
                optionMenu.findItem(R.id.action_refresh).setIcon(R.drawable.ic_action_refreshed);
            }
            return true;
        }

        @Override
        public boolean onMenuOpened(int featureId, Menu menu){
            Typeface typeface = Typeface.createFromAsset(getAssets(), "TitilliumWeb-Regular.ttf");
            menuItemView = (TextView)findViewById(R.id.action_select);
            menuItemView.setTypeface(typeface);
            return super.onMenuOpened(featureId, menu);
        }

        @Override
        public boolean onCreatePanelMenu(int featureId, Menu menu)
        {
            Typeface typeface = Typeface.createFromAsset(getAssets(), "TitilliumWeb-Regular.ttf");
            menuItemView = (TextView)findViewById(R.id.action_select);
            menuItemView.setTypeface(typeface);
            return super.onCreatePanelMenu(featureId, menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item){
            Log.d("GraphActivity", "onOptionsItemSelected");
            Typeface typeface = Typeface.createFromAsset(getAssets(), "TitilliumWeb-Regular.ttf");
            menuItemView = (TextView)findViewById(R.id.action_select);
            menuItemView.setTypeface(typeface);
            int id = item.getItemId();
            if(id == R.id.action_settings){
                Intent intent = new Intent(GraphActivity.this, SettingsActivity.class);
                startActivity(intent);
            }else if(id == R.id.action_refresh){
                if(itemClickable){
                    TaskManager taskManager = new TaskManager(GraphActivity.this, progressBar);
                    taskManager.runTask("online");
                }
            }else if(id == R.id.action_current){
                graphManager.setSelect(GraphManager.select_current);
                String title = optionMenu.findItem(R.id.action_current).getTitle().toString();
                optionMenu.findItem(R.id.action_select).setTitle(title);
                setSelectable(WEEK_button);
                setSelectable(MONTH_button);
                setClickable(YEAR_button);
                graph();
            }else if(id == R.id.action_previous){
                graphManager.setSelect(GraphManager.select_previous);
                String title = optionMenu.findItem(R.id.action_previous).getTitle().toString();
                optionMenu.findItem(R.id.action_select).setTitle(title);
                setSelectable(WEEK_button);
                setSelectable(MONTH_button);
                setClickable(YEAR_button);
                graph();
            }else if(id == R.id.action_compare){
                graphManager.setSelect(GraphManager.select_compare);
                graphManager.setPeriod(GraphManager.period_year);
                String title = optionMenu.findItem(R.id.action_compare).getTitle().toString();
                optionMenu.findItem(R.id.action_select).setTitle(title);
                setNonSelectable(WEEK_button);
                setNonSelectable(MONTH_button);
                setHighLight(YEAR_button);
                setNotClickable(YEAR_button);
                graph();
            }
            return super.onOptionsItemSelected(item);
        }
Job Slot
  • 69
  • 1
  • 6

1 Answers1

-3

You can customize the option menu, including:

  1. Add a custom font

  2. Change font size

  3. Change font color

  4. Set background to a Drawable resource (e.g. image, border, gradient)

To change background to a border or gradient you have to create a resource folder in res called drawable and, inside it, create the border XML or gradient XML.

This can all be done programatically as shown below:

public class CustomMenu extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.cool_menu, menu);
        getLayoutInflater().setFactory(new Factory() {
            public View onCreateView(String name, Context context,
                    AttributeSet attrs) {

                if (name.equalsIgnoreCase(
                        "com.android.internal.view.menu.IconMenuItemView")) {
                    try {
                        LayoutInflater li = LayoutInflater.from(context);
                        final View view = li.createView(name, null, attrs);
                        new Handler().post(new Runnable() {
                            public void run() {
                                // set the background drawable if you want that
                                //or keep it default -- either an image, border
                                //gradient, drawable, etc.
                                view.setBackgroundResource(R.drawable.myimage);
                                ((TextView) view).setTextSize(20); 

                                // set the text color
                                Typeface face = Typeface.createFromAsset(
                                        getAssets(),"OldeEnglish.ttf");     
                                ((TextView) view).setTypeface(face);
                                ((TextView) view).setTextColor(Color.RED);
                            }
                        });
                        return view;
                    } catch (InflateException e) {
                        //Handle any inflation exception here
                    } catch (ClassNotFoundException e) {
                        //Handle any ClassNotFoundException here
                    }
                }
                return null;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.AboutUs:
            Intent i = new Intent("com.test.demo.ABOUT");
            startActivity(i);
            break;
        case R.id.preferences:
            Intent p = new Intent("com.test.demo.PREFS");
            startActivity(p);
            break;
        case R.id.exit:
            finish();
            break;
        }
        return false;
    }
}

Dont forget to create folder called menu in res folder, and inside the menu folder create an XML for your menu (e.g. cool_menu.xml) such as this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item  android:title="about"android:id="@+id/AboutUs" /> 
    <item android:title="Prefs" android:id="@+id/preferences" /> 
    <item android:title="Exit" android:id="@+id/exit" /> 
</menu>

Then the output will be something like this:

enter image description here

ashkufaraz
  • 5,179
  • 6
  • 51
  • 82