简体   繁体   English

如何添加菜单项

[英]how to add menu items

Like the older version of android studio menu is not pre generated. 像旧版本的android studio菜单不是预先生成的。 So I tried and added some code of my own. 因此,我尝试并添加了一些自己的代码。 But unfortunately I am unable to add menu items. 但是很遗憾,我无法添加菜单项。 So need some help:( 所以需要一些帮助:(

MainActivity: 主要活动:

package com.buckydroid.materialapp;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }
}

Menu xml: 菜单XML:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
  <item
      android:title="next"
      android:orderInCategory="100"
      android:icon="@drawable/refresh"
      app:showAsAction="always"
      />
</menu>

app_bar: app_bar:

<?xml version="1.0" encoding="utf-8"?>
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="@color/colorPrimary"
    android:title="@string/app_name"
    android:titleTextColor="#fff"


    >

</Toolbar>

So if you need any other codes then comment :( 因此,如果您需要其他任何代码,请注释:(

Change your code in MainActivity.java 在MainActivity.java中更改代码

from

  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

To

@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);

    return super.onCreateOptionsMenu(menu);
}

I hope it will fix the problem... 我希望它可以解决问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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