【问题标题】:how to add menu items如何添加菜单项
【发布时间】:2017-02-18 01:41:12
【问题描述】:

像老版本的android studio 菜单没有预先生成。所以我尝试并添加了一些我自己的代码。但不幸的是,我无法添加菜单项。所以需要一些帮助:(

主活动:

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);
    }
}

菜单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:

<?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>

所以如果你需要任何其他代码然后评论:(

【问题讨论】:

  • 你能分享主活动xml文件吗?

标签: java android android-layout material-design


【解决方案1】:

在 MainActivity.java 中更改您的代码

来自

  @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 onPrepareOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);

    return super.onCreateOptionsMenu(menu);
}

我希望它能解决问题...

【讨论】:

  • 我仍然面临问题:(
  • 哦,让我再看看
猜你喜欢
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 2013-12-23
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多