Today we will look into Android ActionBar. Action Bar is one of the important part of any application, whether it’s a web application or a mobile app. Today we will learn how to implement action bar in android apps using ActionBar component.

今天,我们将研究Android ActionBar。 动作栏是任何应用程序的重要部分之一,无论它是Web应用程序还是移动应用程序。 今天,我们将学习如何使用ActionBar组件在android应用中实现操作栏。

Android ActionBar (Android ActionBar)

Android ActionBar is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items which become visible when the user clicks the “menu” button.

Android ActionBar是一个菜单栏,它贯穿android中的活动屏幕顶部。 Android ActionBar可以包含菜单项,这些菜单项在用户单击“菜单”按钮时变为可见。

In general an ActionBar consists of the following four components:

通常, ActionBar由以下四个组件组成:

  • App Icon: App branding logo or icon will be displayed here应用程序图标 :应用程序品牌徽标或图标将显示在此处
  • View Control: A dedicated space to display Application title. Also provides option to switch between views by adding spinner or tabbed navigation视图控件 :用于显示应用程序标题的专用空间。 还提供了通过添加微调器或选项卡式导航在视图之间切换的选项
  • Action Buttons: Some important actions of the app can be added here操作按钮 :可以在此处添加应用程序的一些重要操作
  • Action Overflow: All unimportant action will be shown as a menu动作溢出 :所有不重要的动作将显示为菜单

Android ActionBar设置 (Android ActionBar Setting Up)

All activities that use the theme Theme.Holo or a theme derived from Theme.Holo will automatically contain an ActionBar.

使用主题Theme.Holo或派生自Theme.Holo的主题的所有活动将自动包含一个ActionBar。

Android ActionBar菜单 (Android ActionBar Menu)

The simplest way to get toolbar icons and action overflow items into the action bar is by creating menu XML resource file found in res/menu folder. We can add menu items in the raw xml file present in the folder as follows:

使工具栏图标和操作溢出项进入操作栏的最简单方法是创建在res / menu文件夹中找到的菜单XML资源文件。 我们可以在文件夹中存在的原始xml文件中添加菜单项,如下所示:

menu_main.xml

menu_main.xml

<menu xmlns:android="https://schemas.android.com/apk/res/android"xmlns:app="https://schemas.android.com/apk/res-auto"xmlns:tools="https://schemas.android.com/tools" tools:context=".MainActivity"><itemandroid:id="@+id/add" android:icon="@android:drawable/ic_menu_add" app:showAsAction="always"   android:title="@string/add"/><itemandroid:id="@+id/reset" android:icon="@android:drawable/ic_menu_revert" app:showAsAction="always|withText" android:title="@string/reset"/><itemandroid:id="@+id/about" android:icon="@android:drawable/ic_dialog_info" app:showAsAction="never" android:title="@string/about"></item><itemandroid:id="@+id/exit"  app:showAsAction="never" android:title="@string/exit"></item>
</menu>

There are four things that are needed to be configured for every menu item.

每个菜单项都需要配置四件事。

  1. android:id: attribute specifies the id of the menu item. This works like ids anywhere else in the Android app. An android:id value starting with a @+id/ will create a constant in the R.menu constant collectionandroid:id :属性指定菜单项的ID。 这就像在Android应用中其他任何地方的ID一样工作。 以@ + id /开头的android:id值将在R.menu常量集合中创建一个常量
  2. android:title: attribute value contains the title of the menu itemandroid:title :属性值包含菜单项的标题
  3. android:icon: attribute references an icon in the drawable directoriesandroid:icon :属性引用可绘制目录中的图标
  4. android:showAsAction: This attribute indicates how the given item should be portrayed in the action bar.

    We can choose from any of the flags mentioned below:

    • always to keep it in the ActionBar at all times
    • ifRoom to keep it only if space is available
    • never this means that the menu item will not be placed in the ActionBar as an icon. It will only be visible when the menu button is clicked, in the menu that’s popping up
    • |withText : we can append this to either always or ifRoom, to indicate that the toolbar button to be both the icon and the title, not just the icon

    android:showAsAction :此属性指示应如何在操作栏中显示给定的项目。

    我们可以从以下提到的任何标志中进行选择:

    • 始终将其始终保存在ActionBar中
    • ifRoom仅在有可用空间时保留它
    • 从不意味着菜单项不会作为图标放在ActionBar中。 仅当在弹出菜单中单击菜单按钮时,该菜单才会显示
    • | withText :我们可以将其附加到always或ifRoom上,以指示工具栏按钮既是图标又是标题,而不仅仅是图标

Note that always is not guaranteed to be a toolbar button – if you ask for 100 always items, you will not have room for all of them. However, always items get priority for space in the action bar over ifRoom items.

请注意, 始终不能保证始终将其作为工具栏按钮-如果您要求提供100个始终项,则将没有空间容纳所有这些项目。 但是,在操作栏中,项目alwaysifRoom项目优先获得空间。

将菜单扩展到Android ActionBar中 (Inflating the Menu Into the Android ActionBar)

In order for the menu items defined in the menu XML file to be displayed, you need to inflate the menu file. We do so inside the onCreateOptionsMenu() method of the activity where we wish to add the ActionBar. Here is the code snippet:

为了显示在菜单XML文件中定义的菜单项,您需要给菜单文件充气。 我们在要添加ActionBar的活动的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;
}

The R.menu.menu_main parameter is the constant referring to the menu XML file. The menu parameter is the menu into which we want to inflate the menu items.

R.menu.menu_main参数是引用菜单XML文件的常量。 menu参数是我们要在其中添加菜单项的菜单。

响应Android操作栏事件 (Responding to Android Action Bar Events)

To find out when the user taps on one of these things, we’ll need to override onOptionsItemSelected() from the MainActivity as shown below:

为了找出用户何时点击其中一项,我们需要从MainActivity中覆盖onOptionsItemSelected() ,如下所示:

@Override
public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) {case R.id.add://add the function to perform herereturn(true);case R.id.reset://add the function to perform herereturn(true);case R.id.about://add the function to perform herereturn(true);case R.id.exit://add the function to perform herereturn(true);
}return(super.onOptionsItemSelected(item));
}

Now let’s assign some basic functions to each menu items in our project.

现在让我们为项目中的每个菜单项分配一些基本功能。

项目结构 (Project Structure)

Android ActionBar示例代码 (Android ActionBar Example Code)

We’ve implemented the four menu items in the MainActivity as shown in the snippet below:

我们已经在MainActivity中实现了四个菜单项,如下面的代码片段所示:

MainActivity.java

MainActivity.java

package com.journaldev.actionbar;import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {TextView count;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic 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;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) {case R.id.add:count=(TextView)findViewById(R.id.textView);count.setText("Add is clicked");return(true);case R.id.reset:count=(TextView)findViewById(R.id.textView);count.setText("Nothing is selected");return(true);case R.id.about:Toast.makeText(this, R.string.about_toast, Toast.LENGTH_LONG).show();return(true);case R.id.exit:finish();return(true);}return(super.onOptionsItemSelected(item));}
}

The items are assigned their respective functions. The item selected is determined from its id that was defined in the menu_main.xml file.

为项目分配了各自的功能。 所选项目由menu_main.xml文件中定义的ID决定。

Here we just change the TextView contents in the first two items, display a toast in the third and exit the application in the fourth item.

在这里,我们只需更改前两个项目中的TextView内容,在第三个项目中显示一个吐司 ,然后在第四个项目中退出应用程序。

Note that the AppCompatActivity is a replacement for the deprecated version of ActionBarActivity.

请注意, AppCompatActivity替代了不推荐使用的ActionBarActivity版本。

The styles.xml file is defined as follows:

styles.xml文件的定义如下:

<resources><!-- Base application theme. --><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"><!-- Customize your theme here. --></style></resources>

As you can see the parent theme uses a derivative of Theme.AppCompat which holds an ActionBar by default(unless you use Theme.AppCompat.Light.NoActionBar class). Hence there is no need to define it explicitly here.

如您所见,父主题使用Theme.AppCompat的派生类,该派生默认情况下保存一个ActionBar(除非您使用Theme.AppCompat.Light.NoActionBar类)。 因此,无需在此处明确定义它。

Android操作栏向后移植 (Android Action Bar Backporting)

  1. Since ActionBar was introduced after Android Honeycomb 3.0, to implement ActionBar when minSdkVersion is 11 or less we need to import the app-compat-v7 jar into our gradle as we have done here to enable backward compatibility由于ActionBar是在Android Honeycomb 3.0之后引入的,因此要在minSdkVersion为11或更小时实现ActionBar,我们需要将app-compat-v7 jar导入到gradle中,因为我们这样做是为了实现向后兼容
  2. Another way is to import and extend the MainActivity with ActionBarSherlock independent of the action bar backport, since this class was introduced after Android 3.0另一种方法是使用ActionBarSherlock导入和扩展MainActivity,而独立于操作栏的反向端口,因为此类是在Android 3.0之后引入的

Below image shows the output produced by our project, you can see that the ActionBar includes the predefined icons. The textview updates the content since add icon was clicked. The textview reverts the content to the original since reset was clicked. When about is clicked, toast notification appears as shown below.

下图显示了我们的项目产生的输出,您可以看到ActionBar包含预定义的图标。 自从单击添加图标以来,textview会更新内容。 自单击重置后,文本视图会将内容还原为原始内容。 单击“关于”时,将显示吐司通知,如下所示。

This brings an end to android action bar example tutorial. You should also read about android custom ActionBar. You can download android ActionBar project from below link.

这结束了android action bar示例教程。 您还应该阅读有关android自定义ActionBar的信息 。 您可以从下面的链接下载android ActionBar项目。

Download Android ActionBar Example Project下载Android ActionBar示例项目

翻译自: https://www.journaldev.com/9357/android-actionbar-example-tutorial

Android ActionBar示例教程相关推荐

  1. Android WebView示例教程

    Android WebView is used to display HTML in an android app. We can use android WebView to load HTML p ...

  2. Android ExpandableListView示例教程

    Welcome to Android ExpandableListView Example Tutorial. In this tutorial we'll implement an Expandab ...

  3. android action bar 风格,Android ActionBar使用教程

    ActionBar的引入方式: 有几种,从 Android 3.0(API lever 11) 开始,所有使用 Theme.Holo 主题(或者它的子类)的 Activity 都包含了 action ...

  4. Android ViewPager示例教程

    ViewPager in Android allows the user to flip left and right through pages of data. In our android Vi ...

  5. 使用DataBinding的Android SearchView示例教程

    Today we will look into Android SearchView widget and develop an application that filters a ListView ...

  6. Android ListView示例教程

    We will learn how to create a simple Android ListView and launch a new activity on selecting a singl ...

  7. Android AsyncTask示例教程

    Today we will look into Android AsyncTask. We will develop an Android example application that perfo ...

  8. Android BroadcastReceiver示例教程

    Today we'll discuss and implement Android BroadcastReceiver that is a very important component of An ...

  9. android jni示例_Android动画示例

    android jni示例 Android Animation is used to give the UI a rich look and feel. Animations in android a ...

最新文章

  1. 每年通过率仅1%的“天才考试”,中国到底应不应该学?
  2. linux 嵌入式串口通信设计目的,基于linux的嵌入式串口通信.doc
  3. exchange 删除邮件
  4. 《汇编语言》王爽—实验五详解
  5. dfs深度优先搜索_图的深度优先搜索(DFS)
  6. 新手CrossApp 之ScrollView小结
  7. PB高拍仪无纸化软件方案
  8. Vulntarget靶场渗透笔记[持续更新中]
  9. 史上最全的WSL安装教程
  10. 原始混合合成器:Arturia Analog Lab for Mac
  11. 手机照片删了怎么恢复
  12. C#栈的实现(数制转换)
  13. keras 中adam_ADAM电影中的照明技巧和窍门
  14. Rabbitmq- 消费者ack机制与发布者消息确认
  15. 如何从网页获取原图片
  16. OsWorkFlow工作流简介
  17. Exception locking surface SurfaceView报错解决
  18. python里面print是什么函数_python print()内置函数
  19. 经典龙格-库塔法(四阶龙格-库塔法)求解求一阶常微分方程相应的特解的Python程序
  20. kafka(三):kafka broker

热门文章

  1. webservice wsdl 生成服务
  2. Delphi调用外部程序详解
  3. [转载] python 运算符重载有什么用_Python运算符重载用法实例分析
  4. [转载] python numpy.random.randn()与numpy.random.rand()的区别 (正态分布公式)(标准正态分布 standard normal distribution
  5. [转载] Python pep8编码规范
  6. React 入门与实战-课时7 虚拟DOM的本质和目的
  7. 正式版的Linux Kernel 5.1来了,非LTS
  8. mysql修改表名,列名,列类型,添加表列,删除表列
  9. centos经常用到的一些文件
  10. javascript div 弹出可拖动窗口