web-dev-qa-db-ja.com

アクションバーの右上にボタンを追加します

デフォルト設定ActionBarがどこにあるかなど、Buttonの右上にボタンを追加する方法はありますか?設定Buttonを削除しましたが、代わりにカスタムButtonを追加したいです。

20
Brejuro

メニューxmlファイルを編集/作成することにより、ボタンを追加できます。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:app="http://schemas.Android.com/apk/res-auto">

    <item
        Android:id="@+id/action_name"
        Android:icon="@drawable/you_resource_here"
        Android:title="Text to be seen by user"
        app:showAsAction="always"
        Android:orderInCategory="0"/>

</menu>

その後、アクティビティで、新しいファイルを作成した場合、onCreateOptionsMenuを編集する必要があります

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_name) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
59
Android

これは簡単かもしれませんが、代わりにツールバーを使用します。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_name:
            //your code
            break;
    }
    return super.onOptionsItemSelected(item);
}
1
Arpit todewale