2015-06-14 48 views
0

我正尝试在我的android应用中使用自定义菜单。我想添加一些菜单项。 为宗旨,我添加下面我menu_main.xml:菜单在自定义工具栏中未显示

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    tools:context=".MainActivity"> 
    <item 
     android:id="@+id/action_settings" 
     android:orderInCategory="100" 
     android:title="@string/action_settings" 
     app:showAsAction="always" /> 

    <item 
     android:id="@+id/contact" 
     android:icon="@drawable/ic_star" 
     android:orderInCategory="2000" 
     android:title="@string/Rate" 
     app:showAsAction="always" /> 
</menu> 

而且在MainActivity:

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

    @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(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) 
     { 
      Toast.makeText(this,"Hello from settings",Toast.LENGTH_LONG).show(); 
      return true; 

     } 
     if (id == R.id.contact) 
     { 
      startActivity(new Intent(this,ContactUs.class)); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

但是,它是不工作的。 我试过一些关于SO的解决方案,但都没有工作。

例如this

请帮我解决这个问题。

回答

1

你必须设置你的工具栏一样

setActionBar(toolbar); 

中的onCreate()

+0

谢谢苏雷什姬!你救了我的夜晚:D – learner

+0

快乐编码.. :) –

+0

其中是定义工具栏 –