如何动态创建菜单项?

时间:2013-03-22 21:25:05

标签: android android-layout dynamic menuitem android-menu

我正在构建一个Android应用程序,我正在尝试构建一个用户可以登录,注销等用户管理系统。如果用户已注销,我想显示一个登录菜单项,如果是用户已登录。如何动态执行此操作?

这是现在的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/add" android:title="Add" android:icon="@drawable/ic_menu_add"/>
  <item android:id="@+id/list" android:title="List" android:icon="@drawable/ic_menu_list"/>
  <item android:id="@+id/refresh" android:title="Refresh" android:icon="@drawable/ic_menu_refresh"/>
  <item android:id="@+id/login" android:title="Login" android:icon="@drawable/ic_menu_login"/>
</menu>

这是我的Java:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.activity_main, menu);
    return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    System.out.println(item.getItemId()==R.id.add);
    if (item.getItemId()==R.id.add)
    {
        //Cannot add spot unless we have obtained the users current location. 
        if((currentLat != 0) && (currentLng != 0))
        {

            System.out.println("loggedin? : "  + auth.isLoggedIn());
            if(!auth.isLoggedIn())
            {
                Toast.makeText(MainActivity.this, "You must be logged in to add a new spot",
                        Toast.LENGTH_LONG).show();
            }
            else
            {


                Intent addIntent = new Intent(MainActivity.this, AddSpot.class);
                Bundle b = new Bundle();
                b.putDouble("currentLat", currentLat);
                b.putDouble("currentLng", currentLng);
                addIntent.putExtras(b);
                startActivity(addIntent);
                return(true);
            }
        }
    }   
    else if(item.getItemId()==R.id.list)
    {
        //Pointless showing them a blank screen if nothing is retrieved from the server
        if(list != null)
        {
            Intent listIntent = new Intent(MainActivity.this, ListLocations.class);
            listIntent.putExtra("list", list);
            startActivity(listIntent);
            return(true);
        }
    }

    if(item.getItemId()==R.id.refresh)
    {
        finish();
        startActivity(getIntent());
        return(true);       
    }

    if(item.getItemId()==R.id.login)
    {
        Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(loginIntent);
        return(true);   
    }

    return(super.onOptionsItemSelected(item));
}

6 个答案:

答案 0 :(得分:101)

如何动态地将菜单项添加到Android活动

public class yourActivity extends Activity {
    ...
    private static final int MENU_ADD = Menu.FIRST;
    private static final int MENU_LIST = MENU.FIRST + 1;
    private static final int MENU_REFRESH = MENU.FIRST + 2;
    private static final int MENU_LOGIN = MENU.FIRST + 3;

    /**
     * Use if your menu is static (i.e. unchanging)
     */
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
        menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
        menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
        menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
        return true;
    }
    */

    /**
     * Gets called every time the user presses the menu button.
     * Use if your menu is dynamic.
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if(enableAdd)
            menu.add(0, MENU_ADD, Menu.NONE, R.string.your-add-text).setIcon(R.drawable.your-add-icon);
        if(enableList)
            menu.add(0, MENU_LIST, Menu.NONE, R.string.your-list-text).setIcon(R.drawable.your-list-icon);
        if(enableRefresh)
            menu.add(0, MENU_REFRESH, Menu.NONE, R.string.your-refresh-text).setIcon(R.drawable.your-refresh-icon);
        if(enableLogin)
            menu.add(0, MENU_LOGIN, Menu.NONE, R.string.your-login-text).setIcon(R.drawable.your-login-icon);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
        case MENU_ADD: doAddStuff(); break;
        case MENU_LIST: doListStuff(); break;
        case MENU_REFRESH: doRefreshStuff(); break;
        case MENU_LOGIN: doLoginStuff(); break;
        }
        return false;
    }

以下具体示例在用户登录时添加了一个MENU_LOGOUT选项。

    private static final int MENU_LOGOUT = MENU.FIRST + 4;

    public boolean onPrepareOptionsMenu(Menu menu) {
        ...
        if(auth.isLoggedIn()) {
            menu.add(0, MENU_LOGOUT, Menu.NONE, R.string.your-logout-text).setIcon(R.drawable.your-logout-icon);
        }
        ...
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        ...
        case MENU_LOGOUT:
            if(auth.isLoggedIn()) {
                doLogout();
            } else {
                Toast.makeText(this, "You must have somehow been logged out between the time the menu button was pressed and now.", Toast.DURATION_LONG).show();
            }
            break;
        ...
    }

这就是它的全部内容。

答案 1 :(得分:7)

你可以调用invalidateOptionsMenu()(注意:需要使用类似actionBarSherlock的兼容性库来访问,以防你需要支持低API版本),然后根据状态更新菜单项。

您可以隐藏登录操作项并显示注销操作项。

您也可以尝试更新图标本身但我从未尝试过。

答案 2 :(得分:5)

在我的情况下,菜单项位于ArrayList中, - 试试这个希望它会帮助你:)

    public getAddress(autocomplete: google.maps.places.Autocomplete): void {
        if (this._canGetAddress) {
            var place: google.maps.places.PlaceResult = autocomplete.getPlace();
            this.address = place['formatted_address'];
            var location = place['geometry']['location'];
            var lat = location.lat();
            var lng = location.lng();
            this.onAreaChanged.emit({areaEntered: true, place: place});
            this.areaInput.nativeElement.setCustomValidity("");
        }
    }

答案 3 :(得分:0)

创建菜单项的简单方法:

Dynamic_PopUpMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
                menu.getMenu().add("AGIL"); // menus items 
                menu.getMenu().add("AGILANBU"); // menus items
                menu.getMenu().add("AGILarasan");
                menu.getMenu().add("Arasan");
                menu.show();
            }
        });

试试这个:)

答案 4 :(得分:0)

很简单

要创建菜单

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

    for (int i = 0; i < list.size(); i++) {
        menu.add(0, i, 0, "Menu Name").setShortcut('5', 'c');
    }

    return true;
}

从点击的菜单中获取详细信息

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId(); //to get the selected menu id
    String name = item.getTitle(); //to get the selected menu name

    return super.onOptionsItemSelected(item);
}

答案 5 :(得分:0)

private void getPopup(final TextView textView, ArrayList<String> arrayList) {
        final PopupMenu popupMenu = new PopupMenu(sContext, textView);
        for (int i = 0; i < arrayList.size(); i++) {
            popupMenu.getMenu().add(arrayList.get(i));
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                textView.setText(item.getTitle());
                return false;
            }
        });
        popupMenu.show();
    }