Java 如何在android的操作栏中创建按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38158953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:02:46  来源:igfitidea点击:

How to create button in Action bar in android

javaandroidxmlbuttonandroid-actionbar

提问by Manikanta Siripella

I am working on android application where i need a button in action bar. These are my activity and java files. So, i need a button at right side of my tool bar. Thanks in advance.

我正在开发 Android 应用程序,我需要在操作栏中有一个按钮。这些是我的活动和 java 文件。所以,我需要在我的工具栏右侧有一个按钮。提前致谢。

content_b2_bdeliveries.xml:

content_b2_bdeliveries.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.ideabiz.riderapplication.ui.B2BDeliveriesActivity"
tools:showIn="@layout/activity_b2_bdeliveries">
//remaining code;
</LinearLayout>

activity_b2_bdeliveries.xml:

活动_b2_bdeliveries.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.ideabiz.riderapplication.ui.B2BDeliveriesActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_b2_bdeliveries" />

</android.support.design.widget.CoordinatorLayout>

B2BDeliveriesActivity.java:

B2BDeliveriesActivity.java:

public class B2BDeliveriesActivity extends AppCompatActivity {
private final String TAG_NAME="B2BActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b2_bdeliveries);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    ActionBar actionBar = getSupportActionBar();
    //Log.d(TAG_NAME,actionBar.toString());
    if (actionBar != null) {
        try {
            actionBar.setDisplayHomeAsUpEnabled(true);
            } catch (Exception e) {
                Crashlytics.logException(e);
                Log.d(TAG_NAME, "Null Pointer from setDisplayHomeAsUpEnabled" + e.getMessage());
                Utilities.issueTokenUpload("Null Pointer from setDisplayHomeAsUpEnabled" + e, sharedPreferences.getInt("tripId", 999999), sharedPreferences.getString("driverPhoneNo", "9999999999"), sharedPreferences.getString("driverName", "default"), getResources().getString(R.string.version));
            }
    }
}

sample requirement picture

样品需求图片

回答by tibbi

its described properly at https://developer.android.com/guide/topics/ui/menus.html#xml. You can create a menu.xml file at "menu" directory, which is at the same level as "drawable" and "layout" directories

它在https://developer.android.com/guide/topics/ui/menus.html#xml正确描述。您可以在“menu”目录下创建一个 menu.xml 文件,该文件与“drawable”和“layout”目录处于同一级别

回答by Onur ?evik

In your activity class, override the following methods if they are not there by default:

在您的活动类中,如果默认情况下不存在以下方法,请覆盖它们:

// create an action bar button
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // R.menu.mymenu is a reference to an xml file named mymenu.xml which should be inside your res/menu directory. 
    // If you don't have res/menu, just create a directory named "menu" inside res
    getMenuInflater().inflate(R.menu.mymenu, menu);
    return super.onCreateOptionsMenu(menu);
}

// handle button activities
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.mybutton) {
    // do something here
    }
    return super.onOptionsItemSelected(item);
}

mymenu.xml

我的菜单文件

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/mybutton"
    android:title=""
    app:showAsAction="always"
    android:icon="@drawable/mybuttonicon"
    />
</menu>

回答by Ahmad Payan

Someone had answered this question before

之前有人回答过这个问题

You have two steps to do that:

你有两个步骤来做到这一点:

  1. Create menu in res/menu (Name it my_menu.xml)

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
    </menu>
    
  2. Override onCreateOptionsMenu and inflate menu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    return true;
    }
    
  1. 在 res/menu 中创建菜单(将其命名为 my_menu.xml)

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
    </menu>
    
  2. 覆盖 onCreateOptionsMenu 和 inflate 菜单

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    return true;
    }
    

Visit : How to add button in ActionBar(Android)?

访问:如何在 ActionBar(Android) 中添加按钮?

回答by Ashish Ranjan

Make a xml file for your menu in res/menudirectory ( menu_main.xmlin this case):

res/menu目录中为您的菜单创建一个 xml 文件(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="com.example.rashish.myapplication.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Button title"
        android:icon="@drawable/buttonicon"
        app:showAsAction="never" />
</menu>

then add these methods in your activity class :

然后在您的活动类中添加这些方法:

@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.
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        //process your onClick here
        return true;
    }

    return super.onOptionsItemSelected(item);
}

回答by Gautam Malik

If you want to customize UI of your ActionBar, then you can use Toolbar as ActionBar. Here are the steps to do the same :

如果您想自定义 ActionBar 的 UI,则可以将 Toolbar 用作 ActionBar。以下是执行相同操作的步骤:

  1. Add below code as a child of AppBarLayout in your activity layout xml.

    <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize" >
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:weightSum="1">
    
                <TextView
                    android:id="@+id/title"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="ActionBar Title"/>
    
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
    
            </LinearLayout>
    
        </android.support.v7.widget.Toolbar>
    
  2. Make your Toolbar as ActionBar by adding the below code in your Activity onCreate() method.

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
  3. In AndroidManifest.xml, add following theme to your activity:

    android:theme="@style/AppTheme.NoActionBar"
    
  4. In styles.xml add following code:

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    
  1. 在您的活动布局 xml 中添加以下代码作为 AppBarLayout 的子项。

    <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize" >
    
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:weightSum="1">
    
                <TextView
                    android:id="@+id/title"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="ActionBar Title"/>
    
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
    
            </LinearLayout>
    
        </android.support.v7.widget.Toolbar>
    
  2. 通过在您的 Activity onCreate() 方法中添加以下代码,将您的 Toolbar 设为 ActionBar。

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
  3. 在 AndroidManifest.xml 中,将以下主题添加到您的活动中:

    android:theme="@style/AppTheme.NoActionBar"
    
  4. 在styles.xml中添加以下代码:

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>