项目实践二 | 青训营笔记
这是我参与「第四届青训营」笔记创作活动的的第12天;
用于记录开发过程中学习到的知识点。
自定义导航栏
BottomNavigationView:这是Google给我们提供的一个专门用于底部导航的View,只需要在新建Activity的时候选择Bottom Navigation Activity,IDE 就会自动使用BottomNavigationView帮你生成好相应的代码了。其中需要要注意的就是<android.support.design.widget.BottomNavigationView android:id="@+id/navigation" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginEnd="0dp" android:layout_marginStart="0dp" android:background="?android:attr/windowBackground" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:menu="@menu/navigation" />app:menu属性了,它指定了导航栏显示的页面菜单是怎样的。
RadioGroup + ViewPager:这是一种比较常见了的,下面 4 个tab的导航按钮,可以切换不同的页面,实现了滑动的页面效果。示例图:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".style2.Style2Activity"> <android.support.v4.view.ViewPager android:id="@+id/fragment_vp" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/tabs_rg" /> <RadioGroup android:id="@+id/tabs_rg" android:layout_width="match_parent" android:layout_height="56dp" android:layout_alignParentBottom="true" android:background="#dcdcdc" android:orientation="horizontal"> <RadioButton android:id="@+id/first_tab" style="@style/Custom.TabRadioButton" android:checked="true" android:drawableTop="@drawable/tab_sign_selector" android:text="首页" /> <RadioButton android:id="@+id/record_tab" style="@style/Custom.TabRadioButton" android:drawableTop="@drawable/tab_record_selector" android:text="记录" /> <RadioButton android:id="@+id/contact_tab" style="@style/Custom.TabRadioButton" android:drawableTop="@drawable/tab_contact_selector" android:text="联系" /> <RadioButton android:id="@+id/settings_tab" style="@style/Custom.TabRadioButton" android:drawableTop="@drawable/tab_setting_selector" android:text="设置" /> </RadioGroup> </RelativeLayout>
Fragment
- 概念:
Fragment可以理解为应用界面中可重复使用的一部分,可以理解为模块化的Activity,是Android3.0新增的概念。
- 与
Activity的联系:Fragment不能独立存在,必须嵌入到Activity中;- 一个
Activity可以运行多个Fragment; Activity是屏幕的主题,而Fragment是Activity的一个组成元素;Fragment有自己的生命周期,接受它自己的事件,并可以在Activity运行时被添加或删除;Fragment的生命周期受Activity生命周期的影响。
Fragment作用:Fragment从Android 3.0后引入;- 在低版本
Android 3.0前使用Fragment,需要采用android-support-v4.jar兼容包; Fragment的设计思想是解决不同分辨率的终端适配问题;
- 生命周期:
- 每个
Fragment实例都有自己的生命周期。当用户浏览且与应用进行交互时,Fragment片段将会在添加、删除、进入或退出屏幕时,会在生命周期的不同状态中转换。
- 每个
- 加载方式:
- 静态加载:
- 在
Activity的Layout.xml布局文件中静态添加。
- 在
- 动态加载:
- 步骤1:在
Activity布局文件中添加Container; - 步骤2:创建
Fragment对象 - 步骤3:将
fragment传入container中
- 步骤1:在
- 静态加载:
Fragment与Activity之间传值:-
Activity向Fragment传值:分为两步:第一步,将传递的对象存在bundle里面,然后给fragment设置传递的参数;第二步,在fragment通过getArguments()拿到bundle,然后通过键来拿到值即可。 -
Fragment向Activity传值:使用回调的方法,在Fragment的.java文件中定义接口、设置变量、及设置接口的方法;在Activity的.java文件中实现接口即可。
-