使用滚动条(ActionBar)

       活动条(ActionBar)是Android3.0的重要更新之一。ActionBar位于传统标题栏的位置,也就是显示屏幕的顶部。ActionBar可显示应用的图标和Activity标题——也就是前面应用的顶部显示的内容。除此之外,ActionBar的右边还可以显示活动项(Action Item)。

      归纳起来,ActionBar提供了如下功能。

  • 显示选项菜单的菜单项(将菜单项显示成Action Item)。
  • 使用程序图标作为返回Home主键或向上的导航操作。
  • 提供交互式View作为Action View。
  • 提供基于Tab的导航方式,可用于切换多个Fragment。
  • 提供基于下拉的导航方式。  

    启用ActionBar

     Android3.0版本已经默认启用了ActionBar,因此只要在AndroidManifest.xml文件的SDK配置中指定了该应用的目标版本高于11(Android3.0的版本号),那么默认就会启用ActionBar。例如如下配置:

    

  <uses-sdk
        android:minSdkVersion="17" />

     指定该应用程序可以部署在Android4.2平台上,同时兼容Android2.3.3及更高版本。如果Android版本高于Android3.0,该应用将会启用ActionBar。

     如果希望关闭ActionBar,可以设置该应用的主题为Xxx.NoActionBar,例如如下配置片段:

    

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.NoActionBar" >

   上面的粗体字代码指定该应用ActionBar功能。一旦关闭了ActionBar,该Android应用将不再使用ActionBar。

   实际项目中,通常推荐使用代码来控制ActionBar的显示、隐藏,ActionBar提供了如下方法来控制显示隐藏。

  • show():显示ActionBar。
  • hide():隐藏ActionBar。  

   如下实例示范了如何通过代码来控制ActionBar的显示和隐藏。

   该实例的布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >
  <Button android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="showActionBar"
      android:text="显示ActionBar"/>
    <Button android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="hideActionBar"
      android:text="隐藏ActionBar"/>

</LinearLayout>

该实例的Activity代码如下:

package org.crazyit.helloworld;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

public class ActionBarTest extends Activity {
    ActionBar actionBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.action_bar_test);
        //获取该Activity的ActionBar
        //只有当应用主题没有关闭ActionBar时,该代码才返回ActionBar
        actionBar=getActionBar();
    }
    //为“显示ActionBar”按钮定义事件处理方法
    public void showActionBar(View source)
    {
        //显示ActionBar
        actionBar.show();
    }
    //为“隐藏ActionBar”按钮定义事件处理方法
    public void hideActionBar(View source)
    {
        //隐藏ActionBar
        actionBar.hide();
        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.action_bar_test, menu);
        return true;
    }

}

上面的程序中第一行粗体字代码调用了getActionBar()方法获取该Activity关联的ActionBar。接下来就可以调用ActionBar的方法来控制它的显示、隐藏。

 运行上面的程序单击“隐藏ActionBar”按钮,将可以看到如图所示界面。

原文地址:https://www.cnblogs.com/wolipengbo/p/3400012.html