无法在操作栏上添加操作按钮

时间:2014-10-15 21:03:37

标签: android android-actionbar

我想在ActionBar上添加一个ActionButton,但它放在溢出上。我做错了什么? 下面是代码文件和主类 /// - main_activity_actions.xml - ///

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action buton -->
<item android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom"/>
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:showAsAction="never" />
</menu>  

// - MainActivity.java - //     package com.example.my_first;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

    static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

@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_activity_actions, 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.
    switch(item.getItemId()){
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.action_settings:
            openSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void openSettings() {
    // TODO Auto-generated method stub

}

private void openSearch() {
    // TODO Auto-generated method stub

}

public void sendMessage(View view){
    //Do something in response to button
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

}

2 个答案:

答案 0 :(得分:2)

如果您希望操作在ActionBar上拥有自己的图标,请尝试更改

android:showAsAction="ifRoom"

android:showAsAction="always"

答案 1 :(得分:1)

将此架构添加到菜单资源:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto" >

然后更改showAsAction属性:

<item android:id="@+id/action_search"
  android:icon="@drawable/ic_action_search"
  android:title="@string/action_search"
  app:showAsAction="ifRoom" />

我花了好几天才弄明白。答案是here