简体   繁体   中英

Is there any simple way to initialize an object of MenuItem in android?

Whenever i try to initialize a menu item i get to implement all these methods, I'm looking for a better way to initialize the MenuItem.

private MenuItem mMenuItem = new MenuItem() {
    @Override
    public int getItemId() {
        return 0;
    }

    @Override
    public int getGroupId() {
        return 0;
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public MenuItem setTitle(final CharSequence charSequence) {
        return null;
    }

    @Override
    public MenuItem setTitle(final int i) {
        return null;
    }

    @Override
    public CharSequence getTitle() {
        return null;
    }

    ......  
};

Is there any possible way to avoid these long methods?

Here is a better way to initialize the MenuItem !! here is the solution

1- first you have to create a custom Class that implements MenuItem then you implement all methods needed . as shown below :

public abstract class MenuItem2 implements MenuItem {

    @Override
    public int getItemId() {
        return 0;
    }

    @Override
    public int getGroupId() {
        return 0;
    }

    @Override
    public int getOrder() {
        return 0;
    }
 .....
   @Override
    public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
        return null;
    }

}

2 - second you can use that custom Class MenuItem2 and initialize only the method that you want .

 MenuItem menuItem = new MenuItem2() {
            @Override
            public int getItemId() {
                return R.id.#####;
            }
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM