2015-10-25 21 views
2

我有下面的代碼,設置工具欄如何添加圖標動作條,當其setSupportActionBar

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    list = (ListView) findViewById(R.id.ListView); 
    toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

    viewPager = (ViewPager) findViewById(R.id.viewpager); 
    setupViewPager(viewPager); 

    tabLayout = (TabLayout) findViewById(R.id.tabs); 
    tabLayout.setupWithViewPager(viewPager); 
    //downloadImage(); 
} 

我要補充這個代碼?

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.main, menu); 

我想在工具欄的操作欄中有圖標怎麼做?

+1

是的,你必須 – Blackbelt

回答

7

是的,你應該添加

@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); 
     return true; 
    } 
//and this to handle actions 
    @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(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

添加圖標,進入菜單目錄下的main.xml並添加

<item android:id="@+id/action_settings" 
     android:title="@string/action_settings" 
     android:icon="@drawable/icon" 
     android:orderInCategory="100" 
     app:showAsAction="always" /> 
+0

我應該返回return(super.onCreateOptionsMenu(menu)); ? – Moudiz

+0

你應該先調用super並返回true。 –

+0

@EugenPechanec我加這個,它的工作..這是正確的嗎? public boolean onCreateOptionsMenu(菜單菜單){ //充氣菜單;這會將項目添加到操作欄(如果存在)。 MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main,menu); return(super.onCreateOptionsMenu(menu)); } – Moudiz

2

是的,你需要的代碼。所以,你想有一個XML文件,你可以把它叫做「main_menu.xml」

然後添加以下代碼

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

    <item 
     android:id="@+id/action_mainMenu2" 
     android:icon=add drawable 
     android:orderInCategory="10" 
     android:title="Main Menu" 
     app:showAsAction="ifRoom|withText" /> /> 

</menu> 

只要確保你把你的繪製在這裏「機器人:圖標= 添加繪製 「它會出現。祝好運並玩得開心點!