经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Android编程示例:创建机场计划模拟器应用程序
来源:cnblogs  作者:九天飞翼  时间:2018/12/24 10:29:57  对本文有异议

在本文中,我们将演示如何使用Android Studio和Java编程语言创建一个示例Android应用程序,从“临时”实现高级响应用户界面的功能。本文中讨论的应用程序将实现机场航班时刻表模拟的功能。在开发生命周期中,我们将实现Android应用程序的响应式用户界面,用于呈现“到达”和“离开”航班的列表,并提供动态生成和更新实时模式中的航班信息的功能。

我们将大力强调几个Java语言编程方面,并深入研究允许我们提供高级Android应用程序的编程技术的数量,包括从一开始就创建响应app's drawer和navigation bar应用程序的方面,提供我们自己的custom views并且layouts,如custom search view bar with action button,覆盖默认功能通用app's action bar,保持tabbed layout,渲染recycler views ,不同于listviews或gridviews允许创建的自定义外观的项目lists由应用程序所呈现的数据,与创建各种布局多重嵌套fragments,使用 bottom navigation view等

除了应用程序的界面特定主题,我们还将了解如何创建一个用Java编写的高效代码来实现生成和操作数据内容的功能,以及如何提供操作数据的代码和应用程序的用户界面。

具体来说,我们将实施机场航班时刻表模拟器的功能,该模拟器生成随机航班数据集并通过在实时模式中过滤掉航班来模拟航班到达和延长时间线来操纵这些数据,动态更新航班列表被渲染。为此,我们将使用和讨论诸如使用Android应用程序的后台任务,使用计时器等主题。

背景

先决条件(在我们开始之前...)

在我们开始讨论之前,让我们花点时间仔细研究一下到目前为止我们特别需要的开发工具和库来构建和运行我们的第一个Android应用程序。

因为,我们即将使用Java编程语言来部署我们运行Android的第一个应用程序,我们必须安装Java SE。为此,我们需要从http://www.codesocang.com/下载并安装Java Standard Edition - SE平台。反过来,Java SE平台包含在PC上构建和运行用Java编写的代码所需的所有库和模块。

在我们成功安装Java SE平台之后,我们还需要正确安装IDE和创建Android应用程序项目所需的特定库,并构建运行我们正在部署的应用程序的代码。各种IDE,编程语言和库的数量,例如由Android开发社区授权的Microsoft Visual Studio / C#.NET Xamarin或Android Studio,可以有效地用于创建和部署Android应用程序。

在本文中,为了提供Android应用程序开发生命周期的效率,平台兼容性以及开发流程,我们将特别使用Android Studio和Java编程语言来实现此目的。

这就是为什么,在我们在之前的配置步骤中安装Java SE平台之后,需要并强烈建议在开发机器上下载并安装Android Studio(https://developer.android.com/studio/)。

我们可能已经注意到,安装的Android Studio包含许多开发工具,包括IDE,Java SDK和NDK库,Android系统模拟器,Gradle / Maven - java编译器的“make”实用程序,可以更轻松地编译和编译用Java编程语言编写的链接代码。

反过来,Android Studio的IDE是一个高效且响应迅速的工具,用于轻松创建和编辑Android源码以及实现基本应用程序功能的Java代码。

除了高效便捷的IDE之外,Android Studio软件包还包括为各种目标(手机,平板电脑,可穿戴设备,Android电视......)开发Android应用程序所需的Java SDK库。具体来说,Android Studio IDE允许通过SDK管理器下载和安装适用于各种Android系统版本的SDK,SDK Manager是Android Studio的一部分,或者可选地定期使用Java SDK发行版中的本机SDK管理器。

为了编译和链接正在创建的应用程序,Android Studio的软件包还包括上面提到的Gradle / Maven'make'实用程序。在Android Studio中创建我们的第一个Android应用程序项目时,Gradle组件已下载并配置为与Android Studio的IDE一起使用。每次,当我们构建和运行Android应用程序的项目时,Gradle实用程序正在执行编译和链接特定的任务,例如创建包含内置Android应用程序的apk包,可以在模拟器上运行或者一个Android设备。在开发生命周期中,由于已经创建和配置了项目,因此我们可以使用Gradle实用程序的多个版本,就像在本文的项目创建部分中讨论的那样。 

为了能够在调试开发阶段运行应用程序,Android Studio还包括一个支持各种Android系统版本的Android设备模拟器,可通过Android Studio的模拟器管理器从Google和Android开发社区网站源码下载。在模拟器上运行应用程序与在目标Android设备上运行应用程序非常相似。

在本文的下一部分中,我们将演示如何在安装的Android Studio环境中创建我们的第一个Android应用程序项目。

摘要

创建您的第一个Android App项目

在我们成功满足上面讨论的所有安装和配置要求之后,我们要做的第一件事就是运行Android Studio并创建一个项目来实现我们的机场航班时刻表模拟Android应用程序功能。为此,我们将使用Android Studio主对话框切换启动新的Android Studio项目选项:

在此之后,Android项目创建对话框将出现在屏幕上:

在这个对话框中,我们必须指定一个应用程序名称(在这种情况下,它是` AirportApp`),公司域(例如,` epsilon.com`)来正确配置应用程序包,项目位置,特别是包name,在我们的例子中是` com.epsilon.airportapp`。在我们提供了创建项目所需的所有信息后,单击此对话框底部的下一个按钮。

在此步骤之后,我们必须正确选择并指定我们的应用程序的目标设备,包括正确的外形(“手机”或“平板电脑”),最小的SDK及其版本,以及Android系统发布版本:

在我们成功选择了目标设备和Android发布版本之后,我们还必须选择一种应用程序的活动。活动通常是java类实现功能,负责应用程序的主窗口创建,事件处理以及完成其他用户交互特定任务。实际上,扩展泛型Activity类或其他派生类的java 类是任何现有Android应用程序的主类:

在这种特殊情况下,我们开始我们的第一个Android应用程序开发生命周期,选择一个空活动作为我们的机场计划模拟器应用程序的主要活动。此外,我们将定制和增强默认的空活动,以提供执行机场计划模拟任务所需的功能。

Android应用程序创建阶段的最后一步是配置基于活动的java类别名,生成特定的活动布局,以及配置应用程序的向后兼容库。为此,我们必须继续下一个配置对话框:

在最后一步中,我指定一个应用程序基于活动的java类名称,该名称将对应于正在生成的特定活动布局xml文件名。此外,我们必须指定是否要提供应用程序与旧版Android的向后兼容性。

由于我们已经配置了应用程序的活动,因此在最后阶段生成特定项目并打开Android Studio的IDE主窗口:

在本文的下一部分中,我们将简要介绍使用Android Studio创建的Android应用程序的项目结构。

Android App的项目结构

在这一点上,让我们仔细看看应用程序项目创建后打开的Android Studio IDE主窗口左上角的应用程序解决方案树。通常,解决方案树显示正在创建的项目的内容,该内容与保存到特定位置的目录结构完全对应(例如,“ D:\ AirportApp ”)。

AndroidManifest.xml中

文件夹“清单”是显示在应用解决方案树顶部的第一个文件夹。它基本上只包含一个文件' AndroidManifest.xml '。以下文件主要包含运行正在创建的应用程序所需的xml格式的所有配置数据。AndroidManifest.xml文件具有以下结构,对于所有Android应用程序都完全相同:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.epsilon.arthurvratz.airportapp">
  4. <application
  5. android:allowBackup="true"
  6. android:icon="@mipmap/ic_launcher"
  7. android:label="@string/app_name"
  8. android:roundIcon="@mipmap/ic_launcher_round"
  9. android:supportsRtl="true"
  10. android:theme="@style/AppTheme.NoActionBar">
  11. <activity android:name=".AirportActivity"
  12. android:theme="@style/AppTheme.NoActionBar"
  13. android:windowSoftInputMode="stateHidden"
  14. android:configChanges="orientation|screenSize|keyboard|keyboardHidden">
  15. <intent-filter>
  16. <action android:name="android.intent.action.MAIN" />
  17. <category android:name="android.intent.category.LAUNCHER" />
  18. </intent-filter>
  19. </activity>
  20. </application>
  21. </manifest>

 

AndroidManifest.xml文件的第二行包含manifest标记,其属性提供命名空间和应用程序的包名称信息。它还包含一个嵌套标签application ,该标签具有定义标签,文本方向和创建的应用程序的一对图标的属性数。由应用程序标签的属性指定的图标和标签基本上显示在应用程序的主窗口中。应用程序标记还包含一个定义默认应用程序主题的属性(例如,android:theme="@style/AppTheme")。或者,我们可能希望修改现有的或向应用程序标记添加更多属性,以便提供应用程序主窗口的自定义外观和行为。例如,我们可能想要更改值android:theme属性,以便我们的应用程序将覆盖默认的泛型并使用其自己的应用程序操作栏实现。为此,我们需要将以下标记的值更改为android:theme="@style/AppTheme.NoActionBar".

通常,application标记具有嵌套标记的数量,例如activity标记,用于提供主应用程序活动的一组配置属性。默认情况下,activity标记只有一个属性,用于定义主应用程序活动的名称(例如android:name=".AirportActivity")。要修改应用程序的主要活动配置参数,我们可能需要向以下标记添加更多属性:

  1. android:theme="@style/AppTheme.NoActionBar"
  2. android:windowSoftInputMode="stateHidden"
  3. android:configChanges="orientation|screenSize|keyboard|keyboardHidden">

 

在这种特殊情况下,我们将以下配置属性添加到activity上面列出的机场计划模拟器应用主标签中。第一个属性是我们之前在application 上面标记中指定的属性的副本。以下属性用于指定将显示正在运行的应用程序中的默认通用应用程序操作栏。第二个属性android:windowSoftInputMode="stateHidden"用于指定在启动应用程序时不会自动呈现的软输入方法。最后一个属性 android:configChanges="orientation|screenSize|keyboard|keyboardHidden"提供应用程序覆盖的配置更改列表。这意味着应用程序将处理以下更改,而不是Android系统。具体来说,应用程序将处理屏幕旋转并根据当前屏幕方向呈现正确的界面布局变化(例如' portrait'或' landscape')。

应用程序标记还包含最内层嵌套标记的数量,例如intent-filter,action和category。在action和category里面的意图标签intent-filter标签指定的主应用程序的入口点。特别是,这些标签指定当前'.AirportActivity' 是主应用程序的活动:

  1. <intent-filter>
  2. <action android:name="android.intent.action.MAIN" />
  3. <category android:name="android.intent.category.LAUNCHER" />
  4. </intent-filter>

 

Gradle脚本

现在,让我们来看看位于应用解决方案树底部的' Gradle Scripts '兄弟。以下文件夹包含配置上一节中提到的gradle'make'实用程序所需的所有脚本文件,包括项目' '或' '模块的两个' build.gradle '文件实例。第一个build.gradle文件包含以下内容:AirportAppapp

  1. // Top-level build file where you can add configuration options common to all sub-projects/modules.
  2. buildscript {
  3. repositories {
  4. google()
  5. jcenter()
  6. }
  7. dependencies {
  8. classpath 'com.android.tools.build:gradle:3.1.3'
  9.  
  10. // NOTE: Do not place your application dependencies here; they belong
  11. // in the individual module build.gradle files
  12. }
  13. }
  14. allprojects {
  15. repositories {
  16. google()
  17. jcenter()
  18. }
  19. }
  20. task clean(type: Delete) {
  21. delete rootProject.buildDir
  22. }

 

以下文件是包含Gradle存储库的基本配置的非xml文件,包括其构建版本(例如 'com.android.tools.build:gradle:3.1.3')。在项目配置期间,以下文件的内容通常保持不变。
 
但是,第二个build.gradle文件特别感兴趣。第二个build.gradle文件基本上包含应用程序的项目模块依赖项的定义。例如:
  1. apply plugin: 'com.android.application'
  2. android {
  3. compileSdkVersion 28
  4. defaultConfig {
  5. applicationId "com.epsilon.arthurvratz.airportapp"
  6. minSdkVersion 24
  7. targetSdkVersion 28
  8. versionCode 1
  9. versionName "1.0"
  10. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  11. }
  12. buildTypes {
  13. release {
  14. minifyEnabled false
  15. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  16. }
  17. }
  18. }
  19. dependencies {
  20. implementation fileTree(dir: 'libs', include: ['*.jar'])
  21. implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
  22. implementation 'com.android.support:support-v4:28.0.0-alpha3'
  23. implementation 'com.android.support:support-v13:28.0.0-alpha3'
  24. implementation 'com.android.support:design:28.0.0-alpha3'
  25. implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
  26. implementation 'com.android.support.constraint:constraint-layout:1.1.2'
  27. testImplementation 'junit:junit:4.12'
  28. androidTestImplementation 'com.android.support.test:runner:1.0.2'
  29. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
  30. implementation 'org.jetbrains:annotations-java5:15.0'
  31. }

 

为了能够使用Android支持库,我们必须v.4,v.7,v.13将以下行添加到此文件的部分:RecyclerViewConstraintLayout dependencies
 
  1. <span Courier New",Courier,mono; font-size: 12px; font-size-adjust: none; font-stretch: 100%; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; line-height: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: pre; word-spacing: 0px;">
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
  2. implementation 'com.android.support:support-v4:28.0.0-alpha3'
  3. implementation 'com.android.support:support-v13:28.0.0-alpha3'
  4. implementation 'com.android.support:design:28.0.0-alpha3'
  5. implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'
  6. implementation 'com.android.support.constraint:constraint-layout:1.1.2'</span>

 

反过来,' gradle-wrapper.properties '和' local.properties '文件都是另一个特别的兴趣:
 
gradle-wrapper.properties:
  1. #Thu Jul 26 06:49:16 EEST 2018
  2. distributionBase=GRADLE_USER_HOME
  3. distributionPath=wrapper/dists
  4. zipStoreBase=GRADLE_USER_HOME
  5. zipStorePath=wrapper/dists
  6. distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

 

local.properties:
  1. ## This file must *NOT* be checked into Version Control Systems,
  2. # as it contains information specific to your local configuration.
  3. #
  4. # Location of the SDK. This is only used by Gradle.
  5. # For customization when using a Version Control System, please read the
  6. # header note.
  7. #Thu Jul 26 15:02:12 EEST 2018
  8. sdk.dir=C\:\\AndroidSDK

在此文件中,我们可以指定gradle实用程序版本或Android SDK位置的绝对路径。为此,我们必须修改这两个文件的以下行:

  1. distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip
  1. sdk.dir=C\:\\Android\AndroidStudio\SDK
注意:如果您的gradle更改的版本> gradle-4.6-all.zip,,那么你就还需要禁用“ 配置需求 ”中的“选项文件”>“ 设置 ”>“ 建立,实施,部署 “> 编译器 ”。

应用程序的活动和布局文件

在我们完全符合所有应用程序的项目配置步骤之后,让我们看看我们未来应用程序的活动java实现文件和主应用程序的布局xml文件。主应用程序的布局文件位于“ res / layout ”文件夹下,名称为“ activity_airport.xml ”。以下文件最初包含' android.support.constraint.ConstraintLayout'标记,这是空应用程序的默认布局。
要修改的主要应用程序的布局,并添加我们的Android应用程序的界面组件,如其他直列布局或控制(即“若干意见”),我们必须使用Android Studio的布局设计或手动编辑以下布局文件:

 

为了能够在Android Studio的设计器中编辑布局,您还必须修改可以位于应用程序项目的“ res / values ”文件夹中的“ styles.xml ” :
 
  1. <resources>
  2.  
  3. <!-- Base application theme. -->
  4. <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
  5. <!-- Customize your theme here. -->
  6. <item name="colorPrimary">@color/colorPrimary</item>
  7. <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
  8. <item name="colorAccent">@color/colorAccent</item>
  9. </style>
  10.  
  11. </resources>

 

 
具体来说,您必须parent将' style'标签的' '属性值更改parent="Theme.AppCompat.Light.DarkActionBar"为  parent="Base.Theme.AppCompat.Light.DarkActionBar"。
 
以下布局是默认的空应用程序布局,将在讨论应用程序的开发生命周期期间进行更改。或者,我们可以通过手动编辑' activity_airport.xml '布局文件来添加对应用程序布局内容的更改:
 
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context=".AirportActivity">
  8.  
  9. <TextView
  10. android:layout_width="wrap_content"
  11. android:layout_height="19dp"
  12. android:text="Hello World!"
  13. app:layout_constraintBottom_toBottomOf="parent"
  14. app:layout_constraintLeft_toLeftOf="parent"
  15. app:layout_constraintRight_toRightOf="parent"
  16. app:layout_constraintTop_toTopOf="parent" />
  17.  
  18. </android.support.constraint.ConstraintLayout>

 

此外,我们将在本文的后续部分之一中提供有关如何使用约束布局来构建响应式应用程序界面的详细指南。
 
我们此时要讨论的最后一个方面是应用程序的主要活动实现文件' com.epsilon.airportapp / AirportActivity.java':
  1. package com.epsilon.airportapp;
  2. import android.support.v7.app.AppCompatActivity;
  3. import android.os.Bundle;
  4. public class AirportActivity extends AppCompatActivity {
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_airport);
  9. }
  10. }

 

以下文件包含在第一个' com.epsilon.airportapp '文件夹中,并包含' AirportActivity'扩展泛型AppCompatActivity'类的java类的声明。最初,AirportActivity类只包含一个重写方法' OnCreate',实现将应用程序布局呈现为正在创建的应用程序的主内容视图的功能。以下方法实现了调用onCreate超类中的' '方法,或者接受主应用程序的布局resource-id' R.layout.activity_airport'的setContentView方法,并为主应用程序的布局提供了基本的呈现功能。将来,我们会修改' AirportActivity''
 

应用程序的主要布局Bluep rint

此时,我们的主要目标是创建机场计划模拟应用程序的主要布局设计草图。更具体地说,主应用程序的布局将具有以下外观:

从上图中可以看出,整个主要机场应用程序的布局包括'SearchView'最顶层的高级变体'TabLayout',其中将呈现两个到达和离开航班列表。每个选项卡将呈现一个'RecyclerView'显示航班列表,' BottomNavigationView'允许导航将在'昨天','现在'和'tommorow'发生的航班列表中。“TabLayout”和“RecyclerView”由特定片段布局呈现,这些布局在切换应用程序的抽屉导航菜单项或选择其中一个特定选项卡后显示。
 
主应用程序的布局主要基于' DrawerLayout'模式,这意味着应用程序的抽屉将在用户切换应用程序主窗口左上角的操作栏按钮时呈现。应用程序的抽屉定期可能包含基于'NavigationView',应用程序主菜单等的抽屉标题。 
 
在此之前,让我们回想一下,这不是项目创建向导生成的标准应用程序布局。此外,我们将讨论如何以编程方式实现机场应用程序的自定义布局。

设计应用程序的主要布局

现在,我们终于维护了机场应用程序的主要布局蓝图,现在是时候创建和编辑一个或多个应用程序的布局文件了。我们要修改的第一个文件是' activity_airport.xml '。由于我们的机场应用程序旨在拥有应用程序的抽屉,我们选择' DrawerLayout'作为主应用程序的布局类型:
 
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!-- Use DrawerLayout as root container for activity -->
  3. <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. android:id="@+id/airport_drawer_layout"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:fitsSystemWindows="true">
  9.  
  10. <include layout="@layout/content_frame"
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content"/>
  13.  
  14. <android.support.design.widget.NavigationView
  15. android:id="@+id/airport_navigation_view"
  16. android:layout_width="wrap_content"
  17. android:layout_height="match_parent"
  18. android:layout_gravity="start"
  19. android:fitsSystemWindows="true"
  20. app:menu="@menu/main_menu"
  21. app:headerLayout="@layout/nav_header_frame"/>
  22.  
  23. </android.support.v4.widget.DrawerLayout>

 

在这种情况下,我们android.support.v4.widget.DrawerLayout在activity_airport.xml文件中使用' '作为根标记。在此之后,我们还需要创建两个嵌套标签,例如' include'标签,它将包含单独文件' content_frame.xml'中包含的以下布局的另一部分,或' android.support.design.widget.NavigationView'标签,声明机场应用程序的标签抽屉布局。遗憾的是,由于使用了抽屉布局,我们无法使用Android Studio的布局设计器修改上面显示的布局,但我们可以使用Android Studio的IDE文本编辑器手动编辑此布局。
应用程序主要布局的包含片段存储在内容框架文件中,如下所示:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent">
  8.  
  9. <LinearLayout
  10. android:id="@+id/search_bar"
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content"
  13. app:layout_constraintBottom_toTopOf="@+id/airport_fragment_container"
  14. app:layout_constraintEnd_toEndOf="parent"
  15. app:layout_constraintHorizontal_bias="1.0"
  16. app:layout_constraintStart_toStartOf="parent"
  17. app:layout_constraintTop_toTopOf="parent"
  18. app:layout_constraintVertical_bias="0.02"
  19. android:focusable="true"
  20. android:focusableInTouchMode="true">
  21.  
  22. <requestFocus />
  23.  
  24. <android.support.v7.widget.SearchView
  25. android:id="@+id/searchable"
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"/>
  28.  
  29. </LinearLayout>
  30.  
  31. <FrameLayout
  32. android:id="@+id/airport_fragment_container"
  33. android:layout_width="match_parent"
  34. android:layout_height="0dp"
  35. android:layout_marginEnd="8dp"
  36. android:layout_marginStart="8dp"
  37. app:layout_constraintBottom_toTopOf="@+id/flights_navigation"
  38. app:layout_constraintEnd_toEndOf="parent"
  39. app:layout_constraintHorizontal_bias="0.0"
  40. app:layout_constraintStart_toStartOf="parent"
  41. app:layout_constraintTop_toBottomOf="@+id/search_bar">
  42.  
  43. </FrameLayout>
  44.  
  45. <android.support.design.widget.BottomNavigationView
  46. android:id="@+id/flights_navigation"
  47. android:layout_width="match_parent"
  48. android:layout_height="wrap_content"
  49. app:layout_constraintBottom_toBottomOf="parent"
  50. app:layout_constraintEnd_toEndOf="parent"
  51. app:layout_constraintHorizontal_bias="1.0"
  52. app:layout_constraintStart_toStartOf="parent"
  53. app:layout_constraintTop_toBottomOf="@+id/airport_fragment_container"
  54. app:menu="@menu/flights_navigation"
  55. android:theme="@style/AppTheme"/>
  56. </android.support.constraint.ConstraintLayout>

 

在这个文件中,我们通常使用' android.support.constraint.ConstraintLayout'标签作为此布局的根标签。以下标记具有内联标记的数量,包括' LinearLayout',其中' android.support.v7.widget.SearchView'标记被声明',FrameLayout'实际上声明了一个框架,将以编程方式替换为特定的片段渲染' RecyclerView',显示一个航班列表,'BottomNavigationView'按时间过滤掉航班的渲染选项。由于我们使用约束布局作为整个内容框架的根,因此必须正确约束所有嵌套视图和布局。与之前的布局不同,可以使用Android Studio的布局设计器成功编辑内容框架布局。这就是我们选择是否编辑特定内容框架文件或使用布局设计器为以下布局中的所有视图提供特定约束的原因。 
 
在这种情况下,互连内容框架中视图的最佳方法是app:layout_constraintTop_toBottomOf向每个视图标记添加特定属性,例如' ',如上面的源代码所示。在这段代码中,我们从最上面的'LinearLayout'视图标签开始垂直和水平地向每个视图标签添加布局约束属性,以垂直方向链接所有这些属性。
 
在这一点上,让我们回到定义应用程序抽屉布局的代码片段。在' DrawerLayout'标签内部声明的另一个视图是' android.support.design.widget.NavigationView'。以下视图主要用于渲染应用程序的抽屉及其菜单,如上图所示。使用导航视图通常需要我们创建另一个应用程序的抽屉布局和特定菜单,为应用程序的抽屉菜单声明项目。
 
要创建这些布局,我们基本上需要在项目的' / res '文件夹中创建一个子文件夹,并创建名为' main_menu.xml ' 的特定菜单布局资源文件:
 
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <menu xmlns:android="http://schemas.android.com/apk/res/android" >
  3. <group android:checkableBehavior="single">
  4. <item
  5. android:id="@+id/flights"
  6. android:icon="@drawable/ic_flight_black_24dp"
  7. android:title="@string/flights" />
  8. <item
  9. android:id="@+id/about"
  10. android:icon="@drawable/ic_star_black_24dp"
  11. android:title="@string/about" />
  12. </group>
  13. </menu>

 

在这个文件中,我们必须声明' menu'标签,并在其中创建group项目的' '。在这种情况下,以下布局包含每个“航班”或“关于”菜单选项的两个项目组,显示在应用程序的抽屉中,标题下方。
 
另一个布局文件' nav_header_frame.xml '包含用户切换时在应用程序抽屉中呈现的布局:
 
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="240dp"
  7. android:background="@drawable/airport_nav_header"
  8. android:gravity="bottom"
  9. android:orientation="vertical"
  10. android:padding="16dp"
  11. android:theme="@style/ThemeOverlay.AppCompat.Dark">
  12.  
  13. <ImageView
  14. android:id="@+id/imageView"
  15. android:layout_width="103dp"
  16. android:layout_height="99dp"
  17. app:srcCompat="@mipmap/ic_launcher_round" />
  18.  
  19. <Space
  20. android:layout_width="352dp"
  21. android:layout_height="10dp" />
  22.  
  23. <TextView
  24. android:id="@+id/airport_app_title"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:fontFamily="Verdana"
  28. android:text="@string/nav_header"
  29. android:textColor="@android:color/background_light"
  30. android:textIsSelectable="false"
  31. android:textSize="30sp" />
  32.  
  33. <TextView
  34. android:id="@+id/airport_app_author"
  35. android:layout_width="match_parent"
  36. android:layout_height="wrap_content"
  37. android:text="@string/airport_app_author" />
  38.  
  39. </LinearLayout>

 

要创建应用程序的抽屉布局,我们将使用特定的' LinearLayout'标签。与其他布局(例如' CostraintLayout')不同,线性布局允许仅在垂直方向上定位所有视图,并且不需要在视图之间设置任何约束。 
 
要定义正确的抽屉布局,我们必须将以下视图标记放置在线性布局内,以及为应用程序的抽屉标题提供背景图像。为此,我们指定以下线性布局属性:' android:background="@drawable/airport_nav_header"'。通常,我们创建的线性布局将包含以下内联视图:
  • ' ImageView' - 用于显示机场应用程序的图标;
  • ' Space' - 在线性布局中创建特定视图之间的间隙;
  • ' TextView' - 打印机场应用程序的标题或作者的详细信息;

最后,由' NavigationView'及其蓝图呈现的应用程序的抽屉布局将具有以下外观:

在本文的下一部分中,我们将了解如何实现主要机场应用程序活动的功能。

使用操作按钮创建自定义SearchView

SearchView是出现在主应用程序窗口顶部的机场计划模拟器应用程序的第一个控件。此时,让我们回到他标记的'content_frame.xml片段,声明搜索视图位于以下布局文件的所有其他视图之前,由' :包裹起来:'.Tandroid.support.v7.widget.SearchViewLinearLayout<font color="#007000" face=""Segoe UI",Arial,Sans-Serif">'</font>

  1. <LinearLayout
  2. android:id="@+id/search_bar"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. app:layout_constraintBottom_toTopOf="@+id/airport_fragment_container"
  6. app:layout_constraintEnd_toEndOf="parent"
  7. app:layout_constraintHorizontal_bias="1.0"
  8. app:layout_constraintStart_toStartOf="parent"
  9. app:layout_constraintTop_toTopOf="parent"
  10. app:layout_constraintVertical_bias="0.02"
  11. android:focusable="true"
  12. android:focusableInTouchMode="true">
  13.  
  14. <requestFocus />
  15.  
  16. <android.support.v7.widget.SearchView
  17. android:id="@+id/searchable"
  18. android:layout_width="match_parent"
  19. android:layout_height="wrap_content"/>
  20.  
  21. </LinearLayout>

 

我们使用线性布局用于确保应用程序启动后搜索视图不会获得焦点。
由于我们SearchView在内容框架中声明了' '标签,因此我们的目标是通过在java中实现特定代码来提供功能和行为(例如,使搜索视图响应),这些代码将即时处理和处理事件。我们的搜索视图。
 
我们可能知道,在这个项目中我们不会使用通用搜索视图和应用程序栏,但会创建我们自己的自定义搜索视图,它结合了通用搜索视图的基本功能和应用程序的操作栏。
 
要使用操作按钮创建自定义搜索视图,我们需要创建一个新的java类,并将其命名为“ SearchableWithButtonView扩展泛型View”类:
 
  1. public class SearchableWithButtonView extends View {
  2. // SearchView basic functionality implementation java-code goes here...
  3. }

 

在本课程中,我们需要实现以下方法。setupSearchableWithButton()是我们需要实现的第一个方法,以便为我们的自定义搜索视图提供特定的外观和行为:
 
  1. public void setupSearchableWithButton() {
  2. // Set background color of the search view
  3. ((ViewGroup)m_SearchView.findViewById(android.support.v7.appcompat.R.id.search_mag_icon).
  4. getParent()).setBackgroundColor(Color.parseColor("#ffffff"));
  5. // Set default custom search of the search view button icon and look of the custom search view
  6. this.setDefaultSearchIcon(); this.setupIconifiedByDefault();
  7. // Set default search hint displayed in the search view's edit text view
  8. m_SearchView.setQueryHint("TYPE HERE...");
  9. // Set default query text and remove focus from the search view
  10. m_SearchView.setQuery("", false); getRootView().requestFocus();
  11. // Instantinate the search view object and set default action button click event listener
  12. m_SearchView.findViewById(android.support.v7.appcompat.R.id.search_mag_icon).
  13. setOnClickListener(new SearchableViewListener());
  14. // Instantinate the search view object
  15. ViewGroup llSearchView = ((ViewGroup)m_SearchView.findViewById(
  16. android.support.v7.appcompat.R.id.search_mag_icon).getParent());
  17. // Instantinate object of the text editable inside the search view
  18. EditText searchEditText = llSearchView.findViewById(
  19. android.support.v7.appcompat.R.id.search_src_text);
  20. // Remove the search view text editable default selection
  21. searchEditText.setSelected(false);
  22. // Set text editable click event listener
  23. searchEditText.setOnClickListener(new SearchableViewListener());
  24. // Set text editable onTextChange listener
  25. searchEditText.addTextChangedListener(new SearchableViewListener());
  26. }

 

在此方法中,我们通过修改背景颜色,搜索视图按钮图标,在应用程序启动时从搜索视图中删除默认选择和焦点来更改通用搜索视图的外观和行为,并且还设置处理程序(即侦听器)各种搜索视图事件,例如单击用作应用程序主操作按钮的搜索视图按钮,文本编辑和文本可编辑视图点击等。
 
这些事件处理程序实现为' SearchableWithButtonView '子类,在其中声明:
 
  1. public class SearchableViewListener
  2. implements OnClickListener, TextWatcher {
  3. @Override
  4. public void onClick(View view) {
  5. // Check if the custom search view button was clicked
  6. if (android.support.v7.appcompat.R.
  7. id.search_mag_icon == view.getId()) {
  8. // If so, perform a check if the default action bar icon was set
  9. if (!isDefaultIcon) {
  10. // If not, set the default icon by invoking setDefaultSearchIcon() method
  11. setDefaultSearchIcon();
  12. // Terminate the onClick handler method execution
  13. return;
  14. }
  15. // Invoke onClick(...) method from the main app's activity class
  16. m_ClickListener.onClick(view);
  17. }
  18. // Otherwise, set navigation-back search icon
  19. else setNavBackSearchIcon();
  20. }
  21. @Override
  22. public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  23. // Invoke the beforeTextChange(...) method from app's activity class (e.g. its parent)
  24. m_TextWatcherListener.beforeTextChanged(charSequence, i, i1, i2);
  25. }
  26. @Override
  27. public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  28. <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;"> // Set navigation-back icon and invoke the onTextChanged(...) method </span>
  29. <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;">// from app's activity class (e.g. its parent)</span>
  30. setNavBackSearchIcon(); m_TextWatcherListener.onTextChanged(charSequence, i, i1, i2);
  31. }
  32. @Override
  33. public void afterTextChanged(Editable editable) {
  34. // Perform a check if the editable string is empty
  35. if (editable.toString().isEmpty())
  36. // If so, set default search view icon
  37. setDefaultSearchIcon();
  38. // Invoke the afterTextChanged(...) method from its parent
  39. m_TextWatcherListener.afterTextChanged(editable);
  40. }
  41. }

 

另外,  “ SearchableWithButtonView”类有以下方法:

下面列出的方法将自定义搜索视图的外观更改为uniconfied:

  1. private void setupIconifiedByDefault() {
  2. // Disable the iconfied mode to make the search view fill the entire area horizontally
  3. m_SearchView.setIconified(false);
  4. m_SearchView.setIconifiedByDefault(false);
  5. }

 

以下方法使用应用程序操作栏按钮的自定义图标替换通用搜索视图的默认图标

  1. private void setDefaultSearchIcon() {
  2. // Replace the default search view icon with the action button icon
  3. this.isDefaultIcon = true;
  4. this.replaceSearchIcon(R.drawable.ic_dehaze_white_24dp);
  5. }

 

以下方法使用导航后退图标替换默认操作栏按钮图标:

  1. private void setNavBackSearchIcon() {
  2. // Check if the default icon was set
  3. if (this.isDefaultIcon == true) {
  4. // If so, replace search view icon with navigation-back icon
  5. this.isDefaultIcon = false;
  6. this.replaceSearchIcon(R.drawable.ic_arrow_back_black_24dp);
  7. // Run the search view icon animation
  8. this.setupAnimation();
  9. }
  10. }

 

以下方法将默认搜索视图按钮图标替换为从应用程序资源中检索到的图标:

  1. private void replaceSearchIcon(int resDefaultIcon) {
  2. // Instantinate search view button icon object and set the custom icon
  3. // by calling setImageDrawable method that accepts the icon object retrieved
  4. // from the app's resources by calling the context's getDrawable(...) method
  5. ((ImageView)m_SearchView.findViewById(android.support.v7.appcompat.R.id.search_mag_icon)).
  6. setImageDrawable(m_Context.getDrawable(resDefaultIcon));
  7. // Start animating icon
  8. this.setupAnimation();
  9. }

 

此方法用于设置搜索视图图标的动画

  1. private void setupAnimation() {
  2. // Instantinate search view icon object
  3. final ImageView searchIconView = m_SearchView.findViewById(
  4. android.support.v7.appcompat.R.id.search_mag_icon);
  5. // Compute the icon's width and height values
  6. int searchIconWidth = searchIconView.getWidth();
  7. int searchIconHeight = searchIconView.getHeight();
  8. // Instantinate RotateAnimation class object and specify the rotation params
  9. RotateAnimation searchIconAnimation = new RotateAnimation(0f, 360f,
  10. searchIconWidth / 2, searchIconHeight / 2);
  11. // Set animation interpolator
  12. searchIconAnimation.setInterpolator(new LinearInterpolator());
  13. // Set animation repeat count
  14. searchIconAnimation.setRepeatCount(Animation.INFINITE);
  15. // Set animation duration
  16. searchIconAnimation.setDuration(700);
  17. // Start animating the icon
  18. searchIconView.startAnimation(searchIconAnimation);
  19. // Perform a delay for 700ms after the icon animation ends
  20. new Handler().postDelayed(new Runnable() {
  21. @Override
  22. public void run() {
  23. searchIconView.setAnimation(null);
  24. }
  25. }, 700);
  26. }

 

通过使用以下方法,我们覆盖了与搜索视图对象一起使用的findViewById(...)方法的基本功能:

  1. // Override the default findViewById method to be used to instantinate
  2. // search view object
  3. private SearchView findSearchViewById(int resId) {
  4. return ((Activity)m_Context).findViewById(resId);
  5. }

 

通过调用这两个方法,我们设置了主应用程序的activity类中使用的click事件监听器和文本更改事件监听器:

  1. public void setSearchButtonClickListener(@Nullable OnClickListener clickListener) {
  2. // Set click listener class object of its parent
  3. m_ClickListener = clickListener;
  4. }
  5. public void setTextWatchListener(@Nullable TextWatcher textWatchListener) {
  6. // Set text change watcher listener class object of its parent
  7. m_TextWatcherListener = textWatchListener;
  8. }

 

现在,由于我们已经使用操作按钮实现了自定义搜索视图,现在是时候将其功能添加到主应用程序的活动中,如下所示:

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_airport);
  5. // Instantinating the drawer layout object
  6. m_DrawerLayout = findViewById(R.id.airport_drawer_layout);
  7. // Instantinating the navigation view object
  8. m_navigationView = findViewById(R.id.airport_navigation_view);
  9. // Instantinating our custom search view object
  10. m_searchableWithButtonView =
  11. new SearchableWithButtonView(AirportActivity.this, R.id.searchable);
  12. // Setting up our custom search view
  13. m_searchableWithButtonView.setupSearchableWithButton();
  14. // Adding the text change watcher listener
  15. m_searchableWithButtonView.setTextWatchListener(new SearchableWithButtonListener());
  16. // Adding the search view action button click event listener
  17. m_searchableWithButtonView.setSearchButtonClickListener(new SearchableWithButtonListener());
  18. // Setup app's drawer menu click event listener
  19. m_navigationView.setNavigationItemSelectedListener(m_NavigationBarListener);
  20. // ...

 

在overriden onCreate方法中,我们通常执行抽屉布局和导航视图对象的即时化,设置我们的自定义搜索视图并添加特定的事件处理程序。要处理各种搜索视图的事件,我们必须声明一个子类' SearchableWithButtonListener'实现' View.OnClickListener'或' TextWatcher'事件处理泛型类:

  1. public class SearchableWithButtonListener implements View.OnClickListener, TextWatcher
  2. {
  3. @Override
  4. public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  5. }
  6. @Override
  7. public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  8. }
  9. @Override
  10. public void afterTextChanged(Editable editable) {
  11. }
  12. @Override
  13. public void onClick(View view) {
  14. // Perform a check if the app's drawer open
  15. if (!m_DrawerLayout.isDrawerOpen(GravityCompat.START))
  16. // If not, open the app's drawer
  17. m_DrawerLayout.openDrawer(GravityCompat.START);
  18. }
  19. }

 

通过本文下一节中讨论的以下类的方法实现的功能。在这种情况下,我们将仅讨论onClick(...)此类中方法的一种实现。以下方法通过调用方法实现应用程序的抽屉打开功能DrawerLayout.openDrawer(...) 。

正如我们在openDrawer(...)处理自定义操作栏单击事件后触发该方法时已经讨论的那样,应用程序的抽屉打开,显示应用程序的主菜单。此时我们还必须通过调用'm_navigationView.setNavigationItemSelectedListener(m_NavigationBarListener)'接受侦听器类对象作为其单个参数的方法来提供菜单项单击事件处理。以下代码实现了重写导航菜单项click事件监听器类:

  1. private class NavigationBarListener implements
  2. NavigationView.OnNavigationItemSelectedListener
  3. {
  4. // This method handles the navigation menu item click events
  5. public boolean onNavigationItemSelected(MenuItem menuItem) {
  6. // set item as selected to persist highlight
  7. menuItem.setChecked(true);
  8. //...
  9.  
  10. if (m_DrawerLayout.isDrawerOpen(GravityCompat.START))
  11. m_DrawerLayout.closeDrawers();
  12. return true;
  13. }
  14. }

 

创建选项卡式应用程序的布局

正如我们已经讨论过的,机场应用程序旨在响应用户的输入并显示各种内容,具体取决于应用程序的抽屉导航菜单中的选项或用户切换的选项卡。特别是在应用程序的抽屉导航菜单中切换“飞行”菜单项后,它通常会呈现选项卡式布局。每个选项卡基本上显示由回收者视图呈现的航班列表。为实现这一点,我们将使用片段。' Fragment'是应用程序布局的动态创建和渲染部分,包含其他布局或视图,或两者兼而有之。

在这种情况下,到目前为止我们要做的是创建特定的片段布局和我们自己的实现内容呈现功能的java类。正如我们已经讨论过的那样,两个标签“到达”和“离开”将出现在主应用程序的窗口中。在每个选项卡中,我们将呈现' RecyclerView'显示已安排的航班列表。为了提供选项卡式布局功能,我们将使用' TabbedLayout'inside inside' LinearLayout',这是FlightsFragment当用户在应用程序的抽屉导航菜单中切换第一个菜单项'flight'时显示的根布局。航班片段布局在' res / layout / fragment_flights.xml '文件中实现:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. android:id="@+id/flights_fragment"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:orientation="vertical"
  9. tools:context=".FlightsFragment">
  10.  
  11. <android.support.design.widget.TabLayout
  12. android:id="@+id/flights_destination_tabs"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. app:tabMaxWidth="0dp"
  16. app:tabMode="fixed"
  17. app:tabGravity="fill">
  18.  
  19. <android.support.design.widget.TabItem
  20. android:id="@+id/arrivals_tab"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:icon="@drawable/ic_flight_land_black_24dp"
  24. android:text="@string/arrivals_tab" />
  25.  
  26. <android.support.design.widget.TabItem
  27. android:id="@+id/departures_tab"
  28. android:layout_width="wrap_content"
  29. android:layout_height="wrap_content"
  30. android:icon="@drawable/ic_flight_takeoff_black_24dp"
  31. android:text="@string/departures_tab" />
  32.  
  33. </android.support.design.widget.TabLayout>
  34.  
  35. <android.support.v4.view.ViewPager
  36. android:id="@+id/flights_destination_pager"
  37. android:layout_width="wrap_content"
  38. android:layout_height="wrap_content"/>
  39.  
  40. <requestFocus/>
  41. </LinearLayout>

 

在航班片段线性布局中,我们声明了两个标签:' android.support.design.widget.TabLayout'和' android.support.v4.view.ViewPager'。第一个标签基本上定义了标签式布局,其中包含两个选项卡,用于“到达”或“离开”航班渲染,显示在主应用程序窗口的搜索视图下方。通过声明第二个标签' ViewPager'我们提供了在一个整个屏幕之间滑动渲染到另一个屏幕的功能。
 
由于选项卡式布局和视图分页器呈现为片段,我们必须创建一个单独的java类FlightsFragment“扩展泛型android.support.v4.app.Fragment”类:
 
FlightsFragmentImpl.java:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import android.net.Uri;
  3. import android.support.v7.widget.LinearLayoutManager;
  4. import android.support.v7.widget.RecyclerView;
  5. import java.util.ArrayList;
  6. public class FlightsFragmentImpl extends android.support.v4.app.Fragment implements
  7. ArrivalsFragment.OnFragmentInteractionListener,
  8. DeparturesFragment.OnFragmentInteractionListener
  9. {
  10. public RecyclerView m_RecyclerView;
  11. public RecyclerView.Adapter m_RecyclerAdapter;
  12. public RecyclerView.LayoutManager m_LayoutManager;
  13. public void setupFlightsRecyclerView(RecyclerView recyclerView, ArrayList<AirportDataModel> dataSet)
  14. {
  15. // Setting the recycler view object
  16. m_RecyclerView = recyclerView;
  17. // Setting the recycler view has a fixed size
  18. m_RecyclerView.setHasFixedSize(true);
  19. // Instantinating the linear layout manager object
  20. m_LayoutManager = new LinearLayoutManager(getContext());
  21. // Setting up the recycler view's layout manager
  22. m_RecyclerView.setLayoutManager(m_LayoutManager);
  23. // Instantinating the flights recycler view's adapter object
  24. // and adding the flights dataset to the flights recycler view's adapter
  25. m_RecyclerAdapter = new FlightsRecyclerAdapter(dataSet, getContext());
  26. // Setting up the <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;">flights recycler view's adapter object</span>
  27. m_RecyclerView.setAdapter(m_RecyclerAdapter);
  28. }
  29. @Override
  30. public void onFragmentInteraction(Uri uri) {
  31. }
  32. }

 

 
FlightsFragment.java:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import android.content.Context;
  3. import android.net.Uri;
  4. import android.os.Bundle;
  5. import android.support.design.widget.TabLayout;
  6. import android.support.v4.view.ViewPager;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. public class FlightsFragment extends FlightsFragmentImpl
  11. {
  12. private TabLayout m_TabLayout;
  13. private ViewPager m_ViewPager;
  14. final private TabSelectedListener
  15. m_TabSelListener = new TabSelectedListener();
  16. public ArrivalsFragment m_ArrivalsFragment;
  17. public DeparturesFragment m_DeparturesFragment;
  18. private class TabSelectedListener implements TabLayout.OnTabSelectedListener
  19. {
  20. @Override
  21. public void onTabSelected(TabLayout.Tab tab) {
  22. m_ViewPager.setCurrentItem(tab.getPosition());
  23. }
  24. @Override
  25. public void onTabUnselected(TabLayout.Tab tab) {
  26. }
  27. @Override
  28. public void onTabReselected(TabLayout.Tab tab) {
  29. }
  30. }
  31. private OnFragmentInteractionListener mListener;
  32. public FlightsFragment() {
  33. // Required empty public constructor
  34. }
  35. public static FlightsFragment newInstance() {
  36. return new FlightsFragment();
  37. }
  38. @Override
  39. public void onCreate(Bundle savedInstanceState) {
  40. super.onCreate(savedInstanceState);
  41. }
  42. @Override
  43. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  44. Bundle savedInstanceState) {
  45. // Inflating the flights fragment view's object
  46. View FlightsFragmentView =
  47. inflater.inflate(R.layout.fragment_flights, container, false);
  48. // Instantinating the tab layout object
  49. m_TabLayout = FlightsFragmentView.findViewById(R.id.flights_destination_tabs);
  50. // Instantinating view pager object
  51. m_ViewPager = FlightsFragmentView.findViewById(R.id.flights_destination_pager);
  52. // Instantinating the tab layout's pager adapter
  53. FlightsDestPagerAdapter pagerAdapter = new FlightsDestPagerAdapter(
  54. getChildFragmentManager(), m_TabLayout.getTabCount());
  55. // Instantinating the arrivals fragment object
  56. m_ArrivalsFragment = ArrivalsFragment.newInstance();
  57. // Instantinating the departures fragment object
  58. m_DeparturesFragment = DeparturesFragment.newInstance();
  59. // Adding the arrivals and departure fragment objects to the view pager adapter
  60. pagerAdapter.add(m_ArrivalsFragment);
  61. pagerAdapter.add(m_DeparturesFragment);
  62. // Setting up the view pager adapter
  63. m_ViewPager.setAdapter(pagerAdapter);
  64. // Adding the generic page sliding event listener
  65. m_ViewPager.addOnPageChangeListener(
  66. new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));
  67. m_TabLayout.addOnTabSelectedListener(m_TabSelListener);
  68. return FlightsFragmentView;
  69. }
  70. public void onButtonPressed(Uri uri) {
  71. if (mListener != null) {
  72. mListener.onFragmentInteraction(uri);
  73. }
  74. }
  75. @Override
  76. public void onAttach(Context context) {
  77. super.onAttach(context);
  78. if (context instanceof OnFragmentInteractionListener) {
  79. mListener = (OnFragmentInteractionListener) context;
  80. } else {
  81. throw new RuntimeException(context.toString()
  82. + " must implement OnFragmentInteractionListener");
  83. }
  84. }
  85. @Override
  86. public void onDetach() {
  87. super.onDetach();
  88. mListener = null;
  89. }
  90. @Override
  91. public void onFragmentInteraction(Uri uri) {
  92. }
  93. public interface OnFragmentInteractionListener {
  94. // TODO: Update argument type and name
  95. void onFragmentInteraction(Uri uri);
  96. }
  97. }

 

为了实现航班片段功能,我们实际上定义了两个java类。第一个类' FlightsFragmentImpl'扩展了泛型' android.support.v4.app.Fragment '并实现了下面讨论的OnFragmentInteractionListener' ArrivalsFragment'和' DepartureFragment'类的' '功能。下面的类只实现了一个方法' setupFlightsRecyclerView(...)',它接受了一个回收器视图对象或ArrayList本文后面讨论的数据集对象的两个参数。此方法的主要目的是设置回收器视图的适配器,该适配器用于保存在其中一个选定选项卡中显示的回收器视图中呈现的数据。
 
另一个类' FlightsFragment'扩展' FlightsFragmentImpl '的功能,并OnCreateView通过向视图页面适配器添加特定的到达和离开片段对象,提供动态设置选项卡布局和在'覆盖方法中查看寻呼机的基本功能。' FlightsDestPagerAdapter'java-class实现了view pager适配器的基本功能:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import android.support.v4.app.Fragment;
  3. import android.support.v4.app.FragmentManager;
  4. import android.support.v4.app.FragmentPagerAdapter;
  5. import java.util.ArrayList;
  6. public class FlightsDestPagerAdapter extends FragmentPagerAdapter {
  7. private ArrayList<Fragment> m_Fragments = new ArrayList<Fragment>();
  8. public FlightsDestPagerAdapter(FragmentManager FragmentMgr, int NumberOfTabs) {
  9. super(FragmentMgr);
  10. }
  11. public void add(Fragment fragment)
  12. {
  13. m_Fragments.add(fragment);
  14. }
  15. @Override
  16. public Fragment getItem(int position) {
  17. return m_Fragments.get(position);
  18. }
  19. @Override
  20. public int getCount() {
  21. return m_Fragments.size();
  22. }
  23. }

 

以下类的实现主要基于使用' ArrayList<Fragment>'用于存储通用' Fragment'类对象数组的功能。
 
最后,要渲染航班片段,我们必须覆盖onNavigationItemSelected(...)' AirportActivity.NavigationBarListener'类中的' '方法。以下方法主要用于处理应用程序抽屉导航菜单中的事件,并具有以下实现:
 
  1. private class NavigationBarListener implements
  2. NavigationView.OnNavigationItemSelectedListener
  3. {
  4. public boolean onNavigationItemSelected(MenuItem menuItem) {
  5. // set item as selected to persist highlight
  6. menuItem.setChecked(true);
  7. // Instantinate the fragment manager transaction coordinator object
  8. m_FragmentTran = m_FragmentMgr.beginTransaction();
  9. // Perform a check if the flights menu item was selected
  10. if (menuItem.getItemId() == R.id.flights)
  11. // If so, replace the airport_fragment_container frame layout
  12. // with specific flight fragment by using its object.
  13. m_FragmentTran.replace(R.id.airport_fragment_container,
  14. FlightsFragment.newInstance());
  15. else if (menuItem.getItemId() == R.id.about) {}
  16. m_FragmentTran.addToBackStack(null); m_FragmentTran.commit();
  17. // Check if the app's drawer is still open
  18. if (m_DrawerLayout.isDrawerOpen(GravityCompat.START))
  19. // If so, close the app's drawer
  20. m_DrawerLayout.closeDrawers();
  21. return true;
  22. }
  23. public void setupInitialFragment()
  24. {
  25. if (m_FragmentMgr == null)
  26. // Instantinate the support fragment manager object
  27. m_FragmentMgr = getSupportFragmentManager();
  28. // Begin fragments transaction
  29. m_FragmentTran = m_FragmentMgr.beginTransaction();
  30. // Add the default flights fragment object and commit transaction
  31. m_FragmentTran.add(R.id.airport_fragment_container,
  32. FlightsFragment.newInstance()).commit();
  33. }
  34. }

 

以下类还实现了另一个方法' setupInitialFragment(...)',用于在应用程序的主活动代码中调用初始片段时,在重写方法' OnCreate(...)'中,当主应用程序的活动被即时化时:
 
  1. protected void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.activity_airport);
  4. //m_ActionToolBar = findViewById(R.id.airport_actionbar);
  5. m_DrawerLayout = findViewById(R.id.airport_drawer_layout);
  6. m_navigationView = findViewById(R.id.airport_navigation_view);
  7. m_flightsNavigationView = findViewById(R.id.flights_navigation);
  8. //setSupportActionBar(m_ActionToolBar);
  9. //this.setupActionBar(R.drawable.ic_dehaze_white_24dp);
  10. m_searchableWithButtonView =
  11. new SearchableWithButtonView(AirportActivity.this, R.id.searchable);
  12. m_searchableWithButtonView.setupSearchableWithButton();
  13. m_searchableWithButtonView.setTextWatchListener(new SearchableWithButtonListener());
  14. m_searchableWithButtonView.setSearchButtonClickListener(new SearchableWithButtonListener());
  15. m_navigationView.setNavigationItemSelectedListener(m_NavigationBarListener);
  16. m_flightsNavigationView.setSelectedItemId(R.id.flights_now);
  17. // Setting up initial fragment to be rendered in the main app's window
  18. m_NavigationBarListener.setupInitialFragment(); this.hideSoftInputKeyboard();
  19. //...
  20. }

 

在本文的下一部分中,我们将讨论如何在航班片段内呈现??回收者视图,显示“到达”或“离开”航班的列表。

在RecyclerView中渲染航班

在回收站视图中渲染航班列表是我们即将在本文中讨论的最终机场应用程序的GUI主题。正如我们已经知道的那样,我们的机场应用程序显示两个“到达”或“离开”航班列表,并以编程方式以类似方式执行。为了呈现航班列表,我们所要做的就是创建两个片段,这些片段将呈现到达航班或离港航班的回收者视图:

fragment_arrivals.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:id="@+id/arrivals_fragment"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:layout_gravity="center_vertical|center_horizontal"
  8. tools:context=".ArrivalsFragment">
  9.  
  10. <android.support.v7.widget.RecyclerView
  11. android:id="@+id/arrivals_recycler_view"
  12. android:scrollbars="vertical"
  13. android:layout_width="match_parent"
  14. android:layout_height="match_parent"/>
  15. </LinearLayout>

 

 
fragment_departures.xml:
 
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:id="@+id/departures_fragment"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:layout_gravity="center_vertical|center_horizontal"
  8. tools:context=".DeparturesFragment">
  9.  
  10. <android.support.v7.widget.RecyclerView
  11. android:id="@+id/departures_recycler_view"
  12. android:scrollbars="vertical"
  13. android:layout_width="match_parent"
  14. android:layout_height="match_parent"/>
  15. </LinearLayout>

 

我们还创建了两个' ArrivalsFragment'和' DeparturesFragment'的java类,它们实现了上面列出的那些片段的功能:
 
ArrivalsFragment.java:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import android.content.Context;
  3. import android.net.Uri;
  4. import android.os.Bundle;
  5. import android.support.v7.widget.RecyclerView;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.view.ViewGroup;
  9. import java.util.ArrayList;
  10. public class ArrivalsFragment extends android.support.v4.app.Fragment {
  11. public RecyclerView m_ArrivalsRecyclerView;
  12. public ArrayList<AirportDataModel> m_ArrivalsDataSet;
  13. public FlightsFragment m_FlightsFragment;
  14. private OnFragmentInteractionListener mListener;
  15. public ArrivalsFragment() {
  16. // Instatinate the airport app's data model and generate set of random flights
  17. m_ArrivalsDataSet = new AirportDataModel().InitModel(20);
  18. }
  19. public static ArrivalsFragment newInstance() {
  20. return new ArrivalsFragment();
  21. }
  22. @Override
  23. public void onCreate(Bundle savedInstanceState) {
  24. super.onCreate(savedInstanceState);
  25. }
  26. @Override
  27. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  28. Bundle savedInstanceState) {
  29. // Inflate the flights fragment layout
  30. View ArrivalsView = inflater.inflate(R.layout.fragment_arrivals, container, false);
  31. // Get flights fragment layout object
  32. m_FlightsFragment =
  33. (FlightsFragment) this.getParentFragment();
  34. // Instantinate arrivals recycler view object
  35. m_ArrivalsRecyclerView =
  36. ArrivalsView.findViewById(R.id.arrivals_recycler_view);
  37. // Invoke setupFlightsRecyclerView method, which is the member of flight fragment class
  38. m_FlightsFragment.setupFlightsRecyclerView(m_ArrivalsRecyclerView, m_ArrivalsDataSet);
  39. return ArrivalsView;
  40. }
  41. // TODO: Rename method, update argument and hook method into UI event
  42. public void onButtonPressed(Uri uri) {
  43. if (mListener != null) {
  44. mListener.onFragmentInteraction(uri);
  45. }
  46. }
  47. @Override
  48. public void onAttach(Context context) {
  49. super.onAttach(context);
  50. if (context instanceof OnFragmentInteractionListener) {
  51. mListener = (OnFragmentInteractionListener) context;
  52. } else {
  53. throw new RuntimeException(context.toString()
  54. + " must implement OnFragmentInteractionListener");
  55. }
  56. }
  57. @Override
  58. public void onDetach() {
  59. super.onDetach();
  60. mListener = null;
  61. }
  62. public interface OnFragmentInteractionListener {
  63. // TODO: Update argument type and name
  64. void onFragmentInteraction(Uri uri);
  65. }
  66. }

 

DeparturesFragment.java:

  1. package com.epsilon.arthurvratz.airportapp;
  2. import android.content.Context;
  3. import android.net.Uri;
  4. import android.os.Bundle;
  5. import android.support.v7.widget.RecyclerView;
  6. import android.view.LayoutInflater;
  7. import android.view.View;
  8. import android.view.ViewGroup;
  9. import java.util.ArrayList;
  10. public class DeparturesFragment extends android.support.v4.app.Fragment {
  11. public RecyclerView m_DeparturesRecyclerView;
  12. public ArrayList<AirportDataModel> m_DeparturesDataSet;
  13. public FlightsFragment m_FlightsFragment;
  14. private OnFragmentInteractionListener mListener;
  15. public DeparturesFragment() {
  16. // Instatinate the airport app's data model and generate set of random flights
  17. m_DeparturesDataSet = new AirportDataModel().InitModel(20);
  18. }
  19. public static DeparturesFragment newInstance() {
  20. return new DeparturesFragment();
  21. }
  22. @Override
  23. public void onCreate(Bundle savedInstanceState) {
  24. super.onCreate(savedInstanceState);
  25. }
  26. @Override
  27. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  28. Bundle savedInstanceState) {
  29. // Inflate the flights fragment layout
  30. View DeparturesView = inflater.inflate(R.layout.fragment_arrivals, container, false);
  31. // Get flights fragment layout object</span>
  32. m_FlightsFragment =
  33. (FlightsFragment) this.getParentFragment();
  34. // Instantinate departures recycler view object</span>
  35. m_DeparturesRecyclerView =
  36. DeparturesView.findViewById(R.id.arrivals_recycler_view);
  37. // Instantinate arrivals recycler view object</span>
  38. m_FlightsFragment.setupFlightsRecyclerView(m_DeparturesRecyclerView, m_DeparturesDataSet);
  39. return DeparturesView;
  40. }
  41. // TODO: Rename method, update argument and hook method into UI event
  42. public void onButtonPressed(Uri uri) {
  43. if (mListener != null) {
  44. mListener.onFragmentInteraction(uri);
  45. }
  46. }
  47. @Override
  48. public void onAttach(Context context) {
  49. super.onAttach(context);
  50. if (context instanceof OnFragmentInteractionListener) {
  51. mListener = (OnFragmentInteractionListener) context;
  52. } else {
  53. throw new RuntimeException(context.toString()
  54. + " must implement OnFragmentInteractionListener");
  55. }
  56. }
  57. @Override
  58. public void onDetach() {
  59. super.onDetach();
  60. mListener = null;
  61. }
  62. public interface OnFragmentInteractionListener {
  63. // TODO: Update argument type and name
  64. void onFragmentInteraction(Uri uri);
  65. }
  66. }

 

在这两个java类中,我们onCreateView(...)通过膨胀航班片段布局对象来调用setupFlightsRecyclerView(...)方法的功能,以调用' FlightFragmentImpl'类的方法:
 
  1. public void setupFlightsRecyclerView(RecyclerView recyclerView, ArrayList<AirportDataModel> dataSet)
  2. {
  3. m_RecyclerView = recyclerView;
  4. m_RecyclerView.setHasFixedSize(true);
  5. m_LayoutManager = new LinearLayoutManager(getContext());
  6. m_RecyclerView.setLayoutManager(m_LayoutManager);
  7. m_RecyclerAdapter = new FlightsRecyclerAdapter(dataSet, getContext());
  8. m_RecyclerView.setAdapter(m_RecyclerAdapter);
  9. }

 

 
使用回收站视图呈现航班列表的另一个重要方面是回收站视图适配器的实施。由于“到达”或“离开”航班的回收者视图都以类似的方式执行数据呈现,我们只需要为特定的回收站视图实施单个航班回收站视图适配器。
 
此外,我们必须为每个航班项目创建一个布局,显示特定航班的信息,如时间,目的地,航空公司代码,航空公司徽标,国家/地区标志和状态:
 
flights_item.xml:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="wrap_content">
  7.  
  8. <TextView
  9. android:id="@+id/flight_time"
  10. android:layout_width="51dp"
  11. android:layout_height="18dp"
  12. android:layout_marginBottom="8dp"
  13. android:layout_marginTop="24dp"
  14. android:text="3:07pm"
  15. android:textAppearance="@style/TextAppearance.AppCompat.Button"
  16. app:layout_constraintBottom_toBottomOf="parent"
  17. app:layout_constraintEnd_toStartOf="@+id/airlines_logo"
  18. app:layout_constraintStart_toStartOf="parent"
  19. app:layout_constraintTop_toTopOf="parent"
  20. app:layout_constraintVertical_bias="0.0" />
  21.  
  22. <ImageView
  23. android:id="@+id/airlines_logo"
  24. android:layout_width="55dp"
  25. android:layout_height="48dp"
  26. android:layout_marginBottom="8dp"
  27. android:layout_marginTop="8dp"
  28. app:layout_constraintBottom_toBottomOf="parent"
  29. app:layout_constraintEnd_toStartOf="@+id/flight_code"
  30. app:layout_constraintStart_toEndOf="@+id/flight_time"
  31. app:layout_constraintTop_toTopOf="parent"
  32. app:srcCompat="@color/text_color_secondary" />
  33.  
  34. <TextView
  35. android:id="@+id/flight_code"
  36. android:layout_width="59dp"
  37. android:layout_height="wrap_content"
  38. android:layout_marginBottom="8dp"
  39. android:layout_marginTop="24dp"
  40. android:text="TextView"
  41. app:layout_constraintBottom_toBottomOf="parent"
  42. app:layout_constraintEnd_toStartOf="@+id/flight_destination"
  43. app:layout_constraintStart_toEndOf="@+id/airlines_logo"
  44. app:layout_constraintTop_toTopOf="parent"
  45. app:layout_constraintVertical_bias="0.0" />
  46.  
  47. <TextView
  48. android:id="@+id/flight_destination"
  49. android:layout_width="68dp"
  50. android:layout_height="wrap_content"
  51. android:layout_marginBottom="8dp"
  52. android:layout_marginTop="24dp"
  53. android:text="TextView"
  54. android:textAppearance="@style/TextAppearance.AppCompat.Body2"
  55. app:layout_constraintBottom_toBottomOf="parent"
  56. app:layout_constraintEnd_toStartOf="@+id/country_flag"
  57. app:layout_constraintStart_toEndOf="@+id/flight_code"
  58. app:layout_constraintTop_toTopOf="parent"
  59. app:layout_constraintVertical_bias="0.0" />
  60.  
  61. <ImageView
  62. android:id="@+id/country_flag"
  63. android:layout_width="51dp"
  64. android:layout_height="42dp"
  65. android:layout_marginBottom="8dp"
  66. android:layout_marginTop="8dp"
  67. app:layout_constraintBottom_toBottomOf="parent"
  68. app:layout_constraintEnd_toStartOf="@+id/flight_status"
  69. app:layout_constraintStart_toEndOf="@+id/flight_destination"
  70. app:layout_constraintTop_toTopOf="parent"
  71. app:srcCompat="@android:color/black" />
  72.  
  73. <TextView
  74. android:id="@+id/flight_status"
  75. android:layout_width="wrap_content"
  76. android:layout_height="20dp"
  77. android:layout_marginBottom="8dp"
  78. android:layout_marginTop="24dp"
  79. android:text="TextView"
  80. app:layout_constraintBottom_toBottomOf="parent"
  81. app:layout_constraintEnd_toEndOf="parent"
  82. app:layout_constraintStart_toEndOf="@+id/country_flag"
  83. app:layout_constraintTop_toTopOf="parent"
  84. app:layout_constraintVertical_bias="0.0" />
  85.  
  86. </android.support.constraint.ConstraintLayout>

 

 
FlightsRecyclerAdapter.java:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import android.content.Context;
  3. import android.support.v7.widget.RecyclerView;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.view.animation.Animation;
  8. import android.widget.ImageView;
  9. import android.widget.TextView;
  10. import java.text.SimpleDateFormat;
  11. import java.util.ArrayList;
  12. public class FlightsRecyclerAdapter extends RecyclerView.Adapter<FlightsRecyclerAdapter.ViewHolder> {
  13. // Provide a reference to the views for each data item
  14. // Complex data items may need more than one view per item, and
  15. // you provide access to all the views for a data item in a view holder
  16. private ArrayList<AirportDataModel> m_DataModel;
  17. private Context m_context;
  18. public static class ViewHolder extends RecyclerView.ViewHolder {
  19. // each data item is just a string in this case
  20. public TextView m_TimeView;
  21. public TextView m_FlightCodeView;
  22. public TextView m_DestView;
  23. public TextView m_StatusView;
  24. public ImageView m_AirlinesLogoView;
  25. public ImageView m_CountryFlagView;
  26. public ViewHolder(View v) {
  27. super(v);
  28. // Instantinate each view object in the flights_item layout
  29. m_TimeView = v.findViewById(R.id.flight_time);
  30. m_FlightCodeView = v.findViewById(R.id.flight_code);
  31. m_DestView = v.findViewById(R.id.flight_destination);
  32. m_StatusView = v.findViewById(R.id.flight_status);
  33. m_AirlinesLogoView = v.findViewById(R.id.airlines_logo);
  34. m_CountryFlagView = v.findViewById(R.id.country_flag);
  35. }
  36. }
  37. // Provide a suitable constructor (depends on the kind of dataset)
  38. public FlightsRecyclerAdapter(ArrayList<AirportDataModel> m_dataModel, Context context) {
  39. m_DataModel = m_dataModel; m_context = context;
  40. }
  41. // Create new views (invoked by the layout manager)
  42. @Override
  43. public FlightsRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
  44. int viewType) {
  45. // create a new view
  46. View v = LayoutInflater.from(parent.getContext())
  47. .inflate(R.layout.flights_item, parent, false);
  48. ViewHolder vh = new ViewHolder(v);
  49. return vh;
  50. }
  51. // Replace the contents of a view (invoked by the layout manager)
  52. @Override
  53. public void onBindViewHolder(ViewHolder holder, int position) {
  54. // Retrieve specific data for each item rendered in the flights recycler view
  55. // and display these values in the specific views in the flights_item layout
  56. holder.m_TimeView.setText(new SimpleDateFormat("HH:mm")
  57. .format(m_DataModel.get(position).m_Time));
  58. holder.m_StatusView.setText(m_DataModel.get(position).m_Status);
  59. holder.m_DestView.setText(m_DataModel.get(position).m_Destination);
  60. holder.m_FlightCodeView.setText(m_DataModel.get(position).m_Airlines.m_Flight);
  61. Context airlines_logo_context = holder.m_AirlinesLogoView.getContext();
  62. String airlines_logo = m_DataModel.get(position).m_Airlines.m_logoResId;
  63. holder.m_AirlinesLogoView.setImageResource(this.getResourceIdFromString(airlines_logo_context, airlines_logo));
  64. Context flag_context = holder.m_CountryFlagView.getContext();
  65. String flag = "flag" + m_DataModel.get(position).m_DestResId;
  66. holder.m_CountryFlagView.setImageResource(this.getResourceIdFromString(flag_context, flag));
  67. // Launching animation of each view in the flights_item layout
  68. setAnimation(holder.m_TimeView, position);
  69. setAnimation(holder.m_StatusView, position);
  70. setAnimation(holder.m_DestView, position);
  71. setAnimation(holder.m_FlightCodeView, position);
  72. setAnimation(holder.m_AirlinesLogoView, position);
  73. setAnimation(holder.m_CountryFlagView, position);
  74. }
  75. public void setAnimation(View view, int pos)
  76. {
  77. // Instantinating the animation object
  78. Animation flightAnimation = android.view.animation.
  79. AnimationUtils.loadAnimation(m_context, R.anim.fade_interpolator);
  80. // Set animation duration
  81. flightAnimation.setDuration(700);
  82. // Starting the animation
  83. view.startAnimation(flightAnimation);
  84. }
  85. // Return the size of your dataset (invoked by the layout manager)
  86. @Override
  87. public int getItemCount() {
  88. return m_DataModel.size();
  89. }
  90. public int getResourceIdFromString(Context context, String resource)
  91. {
  92. return context.getResources().getIdentifier(resource,
  93. "drawable", context.getPackageName());
  94. }
  95. }

 

' FlightsRecyclerViewAdapter'是扩展泛型' RecyclerView.Adapter<FlightsRecyclerAdapter.ViewHolder>' 专业化功能的java类。它实现了将数据绑定到回收器视图所需的基本功能。具体来说,它实现了一个子java类“ViewHolder”,它负责通过调用flight_item布局中的每个视图的对象来呈现每个航班项目。要呈现特定项目,应用程序正在调用onBindViewHolder(...)overriden方法,以编程方式设置要由flights_item布局内的各种视图显示的特定值。

添加航班时刻表模拟功能

正如我们在本文最开始讨论的那样,除了用于呈现特定航班数据的用户界面外,我们还必须实施负责生成航班数据和时间线模拟的功能。在这个应用程序中,我们使用的模式类似于在其他编程语言和框架中经常使用的模型 - 视图 - 控制器。具体来说,在这种特殊情况下,我们将我们的数据模型与执行实际飞行数据集操作的某个数据控制器相结合:
 
AirportDataModel.java:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import java.util.ArrayList;
  3. import java.util.Random;
  4. public class AirportDataModel {
  5. long m_Time;
  6. String m_Status;
  7. String m_Destination;
  8. String m_DestResId;
  9. Airlines m_Airlines;
  10. public class Airlines
  11. {
  12. public Airlines(String logoResId, String flight)
  13. {
  14. this.m_Flight = flight;
  15. this.m_logoResId = logoResId;
  16. }
  17. public String m_logoResId;
  18. public String m_Flight;
  19. }
  20. public AirportDataModel() { }
  21. public AirportDataModel(long curr_time, String status, String dest, String destResId, Airlines airlines)
  22. {
  23. this.m_Airlines = airlines;
  24. this.m_Status = status;
  25. this.m_Destination = dest;
  26. this.m_Time = curr_time;
  27. this.m_DestResId = destResId;
  28. }
  29. public AirportDataModel getRandomFlight() {
  30. Random rand_obj = new Random();
  31. // Instantinate airport flights destination data class object
  32. AirportFlightsDestData flightsData = new AirportFlightsDestData();
  33. // Generate random destination city index
  34.  
  35. int flight_rnd_index = rand_obj.nextInt(
  36. flightsData.m_DestCities.size() - 1);
  37. // Get a string value of a destination city by its random index
  38. String destCity = flightsData.m_DestCities.get(flight_rnd_index);
  39. // Get specific country flag resource id associated with the name of the city
  40. String destResId = flightsData.getFlagResourceByDestCity(destCity);
  41. // Generate letters in the flight code
  42.  
  43. char airline_code_let1 = (char) (rand_obj.nextInt('Z' - 'A') + 'A');
  44. char airline_code_let2 = (char) (rand_obj.nextInt('Z' - 'A') + 'A');
  45. String airline_code = "\0";
  46. // Append letters to the airline_code string value
  47. airline_code += new StringBuilder().append(airline_code_let1).toString();
  48. airline_code += new StringBuilder().append(airline_code_let2).toString();
  49. String flight_code = "\0";
  50. // Generate four digits of the flight code
  51. flight_code += new StringBuilder().append(rand_obj.nextInt(9)).toString();
  52. flight_code += new StringBuilder().append(rand_obj.nextInt(9)).toString();
  53. flight_code += new StringBuilder().append(rand_obj.nextInt(9)).toString();
  54. flight_code += new StringBuilder().append(rand_obj.nextInt(9)).toString();
  55. // Construct a string containing the full airline code
  56. flight_code = airline_code + " " + flight_code;
  57. // Instantinate and construct airlines data object
  58. Airlines airlines = new Airlines(flightsData.m_airlinesResName.get(rand_obj.nextInt(
  59. flightsData.m_airlinesResName.size() - 1)), flight_code);
  60. // Get random status string value
  61. String flight_status = flightsData.m_Status.get(
  62. rand_obj.nextInt(flightsData.m_Status.size() - 1));
  63. // Generate a random flight time
  64.  
  65. int time_hours_sign = rand_obj.nextInt(2);
  66. // Generate an hours offset from the current system time
  67. int time_hours_offset = rand_obj.nextInt(48);
  68. // Get the current system time
  69.  
  70. long currTimeMillis = System.currentTimeMillis();
  71. // Determine the random flight time in ms
  72.  
  73. if (time_hours_sign > 0)
  74. currTimeMillis += time_hours_offset * 3.6e+6;
  75. else currTimeMillis -= time_hours_offset * 3.6e+6;
  76. // Instantinate and return flight item data object based on the
  77. // data previously generated
  78.  
  79. return new AirportDataModel(currTimeMillis,
  80. flight_status, destCity, destResId, airlines);
  81. }
  82. public ArrayList<AirportDataModel> InitModel(int numOfItems)
  83. {
  84. // Init model by generated a list of random flight items
  85. ArrayList<AirportDataModel> newDataModel = new ArrayList<>();
  86. for (int index = 0; index < numOfItems; index++) {
  87. newDataModel.add(this.getRandomFlight());
  88. }
  89. return newDataModel;
  90. }
  91. public ArrayList<AirportDataModel> Simulate(ArrayList<AirportDataModel> dataSet)
  92. {
  93. // Get current system time in ms
  94. long currTimeMillis = System.currentTimeMillis();
  95. // Get a random current time being simulated
  96. currTimeMillis += new Random().nextInt(48) * 3.6e+6;
  97. // Perform a linear search to filter out all flights that already have taken place
  98. for (int index = 0; index < dataSet.size(); index++) {
  99. AirportDataModel item = dataSet.get(index);
  100. if (item.m_Time <= currTimeMillis) {
  101. // Remove current flight item
  102. dataSet.remove(item);
  103. // Generate and add new flight item
  104. dataSet.add(new Random().nextInt(dataSet.size()), getRandomFlight());
  105. }
  106. }
  107. return dataSet;
  108. }
  109. public ArrayList<AirportDataModel> filterByTime(
  110. ArrayList<AirportDataModel> dataSet, long time_start, long time_end) {
  111. ArrayList<AirportDataModel> targetDataSet = new ArrayList<>();
  112. // Perform a linear search to filter out flights which time belongs to a given range
  113. for (int index = 0; index < dataSet.size(); index++) {
  114. AirportDataModel item = dataSet.get(index);
  115. if (item.m_Time > time_start && item.m_Time < time_end)
  116. targetDataSet.add(item);
  117. }
  118. return targetDataSet;
  119. }
  120. }

 

 
在本课程中,我们实现了生成和操纵航班数据所需的所有方法。我们需要做的第一件事就是实现一个getRandomFlight(...)生成随机飞行数据的方法。以下方法基本上依赖于使用静态声明的数据。为此,我们创建了另一个类,它还定义和操作特定于航班的数据:
 
AirportFlightsDestData.java:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. public class AirportFlightsDestData
  5. {
  6. public class CountryCityRel
  7. {
  8. public CountryCityRel(int countryId, int[] cityIds)
  9. {
  10. this.m_cityIds = cityIds;
  11. this.m_countryId = countryId;
  12. }
  13. private int m_countryId;
  14. private int[] m_cityIds;
  15. }
  16. public String getFlagResourceByDestCity(String destCity)
  17. {
  18. int countryId = -1;
  19. // Performing a linear search to find the dest city index
  20. for (int index = 0; index < m_DestCities.size(); index++) {
  21. if (m_DestCities.get(index) == destCity) {
  22. // Performing a linear search to find the dest country and return country-id
  23. for (int country = 0; country < m_CountryCityRelTable.size(); country++) {
  24. int[] cityIds = m_CountryCityRelTable.get(country).m_cityIds;
  25. for (int city = 0; city < cityIds.length && cityIds != null; city++)
  26. countryId = (cityIds[city] == index) ?
  27. m_CountryCityRelTable.get(country).m_countryId : countryId;
  28. }
  29. }
  30. }
  31. return m_countryResName.get(countryId);
  32. }
  33. public List<String> m_DestCities = Arrays.asList(
  34. "Atlanta", "Beijing", "Dubai", "Tokyo", "Los Angeles", "Chicago", "London", "Hong Kong",
  35. "Shanghai", "Paris", "Amsterdam", "Dallas", "Guangdong", "Frankfurt", "Istanbul", "Delhi", "Tangerang",
  36. "Changi", "Incheon", "Denver", "New York", "San Francisco", "Madrid", "Las Vegas", "Barcelona", "Mumbai", "Torronto");
  37. public List<String> m_countryResName = Arrays.asList(
  38. "peoplesrepublicofchina", "unitedstates", "unitedarabemirates", "japan", "unitedkingdom",
  39. "hongkong", "france", "netherlands", "germany", "turkey", "india", "indonesia",
  40. "singapore", "southkorea", "spain", "canada");
  41. public List<String> m_airlinesResName = Arrays.asList(
  42. "aa2", "aeromexico", "airberlin", "aircanada", "airfrance2", "airindia2", "airmadagascar",
  43. "airphillipines", "airtran", "alaskaairlines3", "alitalia", "austrian2", "avianca1",
  44. "ba2", "brusselsairlines2", "cathaypacific21", "china_airlines", "continental",
  45. "croatia2", "dagonair", "delta3", "elal2", "emirates_logo2", "ethiopianairlines4",
  46. "garudaindonesia", "hawaiian2", "iberia2", "icelandair", "jal2", "klm2", "korean",
  47. "lan2", "lot2", "lufthansa4", "malaysia", "midweat", "newzealand", "nwa1", "oceanic",
  48. "qantas2", "sabena2", "singaporeairlines", "southafricanairways2", "southwest2",
  49. "spirit", "srilankan", "swiss", "swissair3", "tap", "tarom", "thai4", "turkish",
  50. "united", "varig", "vietnamairlines", "virgin4", "wideroe1");
  51. public List<CountryCityRel> m_CountryCityRelTable =
  52. Arrays.asList(new CountryCityRel(0, new int[] { 1, 8, 12, }),
  53. new CountryCityRel(1, new int[] { 0, 4, 5, 11, 19, 20, 21,23 }),
  54. new CountryCityRel(2, new int[] { 2 }),
  55. new CountryCityRel(3, new int[] { 3 }),
  56. new CountryCityRel(4, new int[] { 6 }),
  57. new CountryCityRel(5, new int[] { 7 }),
  58. new CountryCityRel(6, new int[] { 9 }),
  59. new CountryCityRel(7, new int[] { 10 }),
  60. new CountryCityRel(8, new int[] { 13 }),
  61. new CountryCityRel(9, new int[] { 14 }),
  62. new CountryCityRel(10, new int[] { 15, 22, 25 }),
  63. new CountryCityRel(11, new int[] { 16 }),
  64. new CountryCityRel(12, new int[] { 17 }),
  65. new CountryCityRel(13, new int[] { 18 }),
  66. new CountryCityRel(14, new int[] { 21, 24 }),
  67. new CountryCityRel(15, new int[] { 26 }));
  68. public List<String> m_Status = Arrays.asList("Check-In", "Canceled", "Expected", "Delayed");
  69. }

 

以下类包含一组List声明和静态初始化的通用“ 对象”,用于保存航班目的地城市的各种数据,以及包含航空公司徽标和国家/地区标志的资源名称列表。此外,以下类具有' getFlagResourceByDestCity'方法的声明,该方法用于通过目标城市的名称检索特定资源名称上的数据。
 
在机场数据模型类中,我们必须声明特定的数据字段变量来保存每个航班上的数据:
 
  1. long m_Time;
  2. String m_Status;
  3. String m_Destination;
  4. String m_DestResId;
  5. Airlines m_Airlines;
  6. public class Airlines
  7. {
  8. public Airlines(String logoResId, String flight)
  9. {
  10. this.m_Flight = flight;
  11. this.m_logoResId = logoResId;
  12. }
  13. public String m_logoResId;
  14. public String m_Flight;
  15. }

 

此外,在这个类中,我们实现下面的方法包括getRandomFlight(...),InitModel(...),Simulate(...)和filterByTime(...)。正如我们已经讨论的那样,getRandomFlight方法用于为随机飞行生成随机数据,稍后将添加到灯光列表中。为此,我们分别在ArrivalsFragment和DeparturesFragment类构造函数中调用InitModel方法,以便这些构造函数中的每一个都将立即启动机场数据模型类对象,调用此方法并接收包含到达列表的数组列表对象的自己的副本或者出发航班:
 
  1. public ArrivalsFragment() {
  2. m_ArrivalsDataSet = new AirportDataModel().InitModel(20);
  3. }

 

要在航班时刻表模拟过程中提供航班动态更新列表,我们必须覆盖应用程序活动类的默认onResume方法,如下所示:
 
  1. @Override
  2. protected void onResume() {
  3. super.onResume();
  4. this.findViewById(R.id.search_bar).requestFocus();
  5. startSimulation();
  6. }

 

在这个方法中,我们调用另一个Simulate(...)方法来启动模拟过程:
 
  1. public void Simulate() {
  2. simTask = new TimerTask() {
  3. @Override
  4. public void run() {
  5. handler.post(new Runnable() {
  6. @Override
  7. public void run() {
  8. // Instantinate flights fragment object
  9. FlightsFragment flightsFragment = (FlightsFragment)
  10. m_FragmentMgr.findFragmentById(R.id.airport_fragment_container);
  11. m_flightsNavigationView.setSelectedItemId(R.id.flights_now);
  12. ArrayList<AirportDataModel> dataSet = null;
  13. RecyclerView recyclerView = null;
  14. // Determine the currently selected tab
  15. TabLayout tabLayout = findViewById(R.id.flights_destination_tabs);
  16. if (tabLayout.getTabAt(0).isSelected()) {
  17. dataSet = flightsFragment.m_ArrivalsFragment.m_ArrivalsDataSet;
  18. recyclerView = flightsFragment.m_ArrivalsFragment.m_ArrivalsRecyclerView;
  19. }
  20. else if (tabLayout.getTabAt(1).isSelected()) {
  21. dataSet = flightsFragment.m_DeparturesFragment.m_DeparturesDataSet;
  22. recyclerView = flightsFragment.m_DeparturesFragment.m_DeparturesRecyclerView;
  23. }
  24. // Invoking airport data model's Simulate method
  25. m_AirportDataModel.Simulate(dataSet);
  26. // Instantinating the new object for FlightsRecyclerAdapter class and
  27. // pass the dataset object as one of the adapter's constructor parameters
  28. FlightsRecyclerAdapter recyclerAdapter
  29. = new FlightsRecyclerAdapter(dataSet, getBaseContext());
  30. // For the current recycler view object setting the new adapter
  31. recyclerView.setAdapter(recyclerAdapter);
  32. // Updating the data bound to the new recycler adapter
  33. recyclerAdapter.notifyDataSetChanged();
  34. recyclerAdapter.notifyItemRangeChanged(0, dataSet.size());
  35. }
  36. });
  37. }
  38. };
  39. }

 

在上面列出的这个方法中,我们创建了一个由timer实例生成的计时器任务线程:
  1. private void startSimulation()
  2. {
  3. this.Simulate(); new Timer().schedule(simTask, 50, 10000);
  4. }

 

每次系统计时器调度时,都会调用run(...)方法。在下面的方法中,我们调用上面列出的机场数据模型的Simulate(...)方法。以下方法确定系统时间并过滤掉时间值小于当前系统时间的所有航班项目。之后我们创建一个前面讨论过的Recycler视图控制器的新实例,并将新的航班列表作为其构造函数的参数传递给它。之后,我们最终调用适配器的notifyDataSetChange(...)和notifyItemRangeChanged(...)方法,使正在更新的数据无效并在Recycler视图中反映其更改。

添加自定义搜索视图功能

正如我们上面已经讨论过的,我们的机场应用程序实现了在应用程序主窗口最顶层呈现的搜索视图,以通过部分匹配执行航班数据的索引搜索。此时,我们要做的就是将搜索功能添加到以下自定义搜索视图中。为此,我们onTextChanged在主应用程序的活动类中实现方法,可以使用按钮监听器进行搜索:

  1. public class SearchableWithButtonListener implements View.OnClickListener, TextWatcher
  2. {
  3. @Override
  4. public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  5. }
  6. @Override
  7. public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  8. // Instantinating the flights fragment object
  9. FlightsFragment flightsFragment = (FlightsFragment)
  10. m_FragmentMgr.findFragmentById(R.id.airport_fragment_container);
  11. RecyclerView flightsRecyclerView = null;
  12. ArrayList<AirportDataModel> DataSet, oldDataSet = null;
  13. // Determining the currently select tab
  14. TabLayout tabLayout = findViewById(R.id.flights_destination_tabs);
  15. if (tabLayout.getTabAt(0).isSelected()) {
  16. // Instantinating the currently active recycler view's object
  17. flightsRecyclerView = flightsFragment.m_ArrivalsFragment.m_ArrivalsRecyclerView;
  18. // Retriving a list of arrival flights
  19. oldDataSet = flightsFragment.m_ArrivalsFragment.m_ArrivalsDataSet;
  20. }
  21. else if (tabLayout.getTabAt(1).isSelected()) {
  22. <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;">
  23. // Instantinating the currently active recycler view's object</span>
  24. flightsRecyclerView = flightsFragment.m_DeparturesFragment.m_DeparturesRecyclerView;
  25. <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;"> // Retriving a list of departure flights</span>
  26. oldDataSet = flightsFragment.m_DeparturesFragment.m_DeparturesDataSet;
  27. }
  28. // Perform a check if the string is not empty
  29.  
  30. if (!charSequence.toString().isEmpty()) {
  31. // If so instantinate the flights indexed search object and invoke doSearch method
  32. // to obtain the list flights which data matches by the partial match
  33. DataSet = new FlightsIndexedSearch().
  34. doSearch(charSequence.toString(), oldDataSet);
  35. if (DataSet.size() == 0) {
  36. DataSet = oldDataSet;
  37. }
  38. }
  39. else DataSet = oldDataSet;
  40. // Instantinate the new adapter object and pass the new filtered dataset as argument
  41. FlightsRecyclerAdapter recyclerAdapter
  42. = new FlightsRecyclerAdapter(DataSet, getBaseContext());
  43. <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; line-height: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;"> // Setting up the new recycler view's adapter</span>
  44. flightsRecyclerView.setAdapter(recyclerAdapter);
  45. <span Segoe UI",Arial,Sans-Serif; font-size: 14px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: normal; word-spacing: 0px;"> // Reflect changes in recycler view</span>
  46. recyclerAdapter.notifyDataSetChanged();
  47. recyclerAdapter.notifyItemRangeChanged(0, DataSet.size());
  48. }
  49. @Override
  50. public void afterTextChanged(Editable editable) {
  51. }
  52. @Override
  53. public void onClick(View view) {
  54. if (!m_DrawerLayout.isDrawerOpen(GravityCompat.START))
  55. m_DrawerLayout.openDrawer(GravityCompat.START);
  56. }
  57. }

 

当用户在搜索视图中键入文本时,将onTextChanged 调用overriden事件处理方法。在此方法中,我们确定当前活动的回收器视图并执行doSearch方法以通过部分匹配获得已过滤的航班物品列表。之后,我们即时启动新适配器并将获取的数据集传递给以下适配器。最后,我们在当前活动的回收站视图中使这些数据无效。下面列出的代码片段包含doSearch方法的实现:
 
  1. package com.epsilon.arthurvratz.airportapp;
  2. import java.util.ArrayList;
  3. import java.util.regex.Pattern;
  4. public class FlightsIndexedSearch {
  5. public ArrayList<AirportDataModel> doSearch(String text,
  6. ArrayList<AirportDataModel> dataSet) {
  7. // Instantinating the empty flights array list object
  8. ArrayList<AirportDataModel> targetDataset = new ArrayList<>();
  9. // Performing a linear search to find all flight items which data values
  10. // match the specific pattern
  11.  
  12. for (int index = 0; index < dataSet.size(); index++) {
  13. AirportDataModel currItem = dataSet.get(index);
  14. // Applying search pattern to the flight destination string value
  15. boolean dest = Pattern.compile(".*" + text + ".*",
  16. Pattern.CASE_INSENSITIVE).matcher(currItem.m_Destination).matches();
  17. // Applying search pattern to the airlines flight code string value
  18. boolean flight = Pattern.compile(".*" + text + ".*",
  19. Pattern.CASE_INSENSITIVE).matcher(currItem.m_Airlines.m_Flight).matches();
  20. // Applying search pattern to the flight status string value
  21. boolean status = Pattern.compile(".*" + text + ".*",
  22. Pattern.CASE_INSENSITIVE).matcher(currItem.m_Status).matches();
  23. // If one of these values matches the pattern add the current item to the
  24. // target dataset
  25.  
  26. if (dest != false || flight != false || status != false) {
  27. targetDataset.add(currItem);
  28. }
  29. }
  30. return targetDataset;
  31. }
  32. }

 

添加底部导航栏功能

底部导航栏的功能与为执行航班索引搜索而提供的功能非常相似。要提供此功能,我们必须在主应用程序的活动类中设置选定侦听器的导航项:

  1. m_flightsNavigationView.setOnNavigationItemSelectedListener(
  2. new BottomNavigationView.OnNavigationItemSelectedListener() {
  3. @Override
  4. public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
  5. FlightsFragment flightsFragment = (FlightsFragment)
  6. m_FragmentMgr.findFragmentById(R.id.airport_fragment_container);
  7. RecyclerView recyclerView = null;
  8. ArrayList<AirportDataModel> dataSet = null;
  9. FlightsRecyclerAdapter recyclerAdapter = null;
  10. // Determining the currently selected tab
  11. TabLayout tabLayout = findViewById(R.id.flights_destination_tabs);
  12. if (tabLayout.getTabAt(0).isSelected()) {
  13. // Getting the currently active recycler view object
  14. recyclerView = flightsFragment.m_ArrivalsFragment.m_ArrivalsRecyclerView;
  15. // Getting the dataset of the currently active recycle view (e.g. arrival flights dataset)
  16. dataSet = flightsFragment.m_ArrivalsFragment.m_ArrivalsDataSet;
  17. }
  18. else if (tabLayout.getTabAt(1).isSelected()) {
  19. // Getting the currently active recycler view object
  20. recyclerView = flightsFragment.m_DeparturesFragment.m_DeparturesRecyclerView;
  21. // Getting the dataset of the currently active recycle view (e.g. departure flights dataset
  22. dataSet = flightsFragment.m_DeparturesFragment.m_DeparturesDataSet;
  23. }
  24. // Get current system time value
  25.  
  26. long curr_time = System.currentTimeMillis();
  27. if (menuItem.getItemId() == R.id.flights_prev)
  28. {
  29. // Instantinating the new recycler adapter object and pass the filtered list of previous flights items
  30. // returned by the filterByTime method
  31. recyclerAdapter = new FlightsRecyclerAdapter(m_AirportDataModel.filterByTime(dataSet,
  32. curr_time - (long)3.6e+6 * 48, curr_time), getBaseContext());
  33. }
  34. else if (menuItem.getItemId() == R.id.flights_now)
  35. {
  36. // Instantinating the new recycler adapter object and pass the filtered list of current flights items
  37. // returned by the filterByTime method
  38. recyclerAdapter = new FlightsRecyclerAdapter(m_AirportDataModel.filterByTime(dataSet,
  39. curr_time - (long)3.6e+6 * 24, curr_time + (long)3.6e+6 * 24), getBaseContext());
  40. else if (menuItem.getItemId() == R.id.flights_next)
  41. {
  42. // Instantinating the new recycler adapter object and pass the filtered list of next flights items
  43. // returned by the filterByTime method
  44. recyclerAdapter = new FlightsRecyclerAdapter(m_AirportDataModel.filterByTime(dataSet,
  45. curr_time, curr_time + (long)3.6e+6 * 48), getBaseContext());
  46. }
  47. // Setting up the new recycler view's adapter
  48. recyclerView.setAdapter(recyclerAdapter);
  49. // Reflect changes in recycler view
  50. recyclerAdapter.notifyDataSetChanged();
  51. recyclerAdapter.notifyItemRangeChanged(0, dataSet.size());
  52. return true;
  53. }
  54. });

 

在这种方法中,我们首先确定当前活动的回收器视图并接收其对象。之后,我们正在检查用户是否切换了特定的底部导航按钮,并通过调用filterByTime方法过滤掉与给定时间线条件匹配的所有航班。最后,我们创建一个新的回收器视图适配器并将数据集传递给它的构造函数,使当前活动的回收器视图无效。

兴趣点

在本文中,我们讨论了使用各种Android和Java编程语言技术创建和开发高级Android应用程序的几个方面,包括创建自定义视图和布局,提供基于导航抽屉的应用程序,处理片段和回收器视图,实现自定义数据适配器和控制器等

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号