第三课 基类的封装

项目源码
https://github.com/liaozhoubei/NetEasyNews/tree/dev_kotlin

一个中大型的应用,通常会有几十上百个页面,这些页面的功能各不相同,那么应该怎样给他们做一个统一的基类呢?

一个好的应用,一般都是有统一的设计,统一的主色调,统一的页面样式,所以即使页面功能不同,也会有相同的地方。那么有哪写地方会相同呢?就目前的普遍应用来看,一个应用会由这几部分组成:

  • 标题栏
  • 加载失败/加载中的页面效果

那么我们就来设计一下这几个部分吧。

标题栏设计

这年头大部分的应用都会由一个标题栏,提醒用户当前处于什么页面。

标题栏一般使用 ToolBar /ActionBar 这两个控件,当然它们也是可以搭配使用的。在这里我们旋转 ToolBar。

首先设计一下ToolBar 的布局,很简单,如下:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
>

    <androidx.appcompat.widget.Toolbar
            android:id="@+id/my_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:minHeight="?attr/actionBarSize"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <TextView
                android:id="@+id/toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:singleLine="true"
                android:textColor="@color/white"
                android:textSize="20sp"/>

    </androidx.appcompat.widget.Toolbar>

</merge>

在这里我们使用到了 <merge> 这个标签,它起到减少布局层级的作用,布局层级过多会导致页面绘制过慢导致的卡顿。

其次在 ToolBar 控件中包着 TextView,这样可以使标题文字居中,如果不设置,标题文字一般会在左边显示。

BaseActivity 设计

所谓基类,就是拥有着子类都能使用的通用方法,所以照着这种思路,可以将子类通用方法都写在 BaseActivity 中,当然要注意这些方法是需要使用 Context 才行的,否则导致 BaseActivity 过于臃肿也不行。

而我们的 ToolBar 是大部分 Activity 或者 fragment 都会使用到的,因此也要放在 BaseActivity 中。

然而有个问题,如果我们用 BaseActivity 写布局,那么子类的 Activity 的布局怎么办?

这其实是个简单的问题,对于熟悉 Android 开发的同学而言,应该对 LayoutInflate.inflate(int resource, ViewGroup root, boolean attachToRoot) 不陌生吧。

使用它就可以把子 Activity 的布局添加到 BaseActivity 中,它的秘密在于 第 2、3 个参数,这里就不扩开讲了,可以查看我的这篇博客 :

Android LayoutInflater 参数详情

https://www.jianshu.com/p/4e98acab2dc8

所以我们的方法是写好 BaseActivity 布局用,设计一个抽象方法,让子类将 Layout 传递过去,直接添加到 BaseActivity 的布局中。

BaseActivity 的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".base.BaseActivity">

    <include
            android:id="@+id/tl_toolbar"
            layout="@layout/toolbar_page"/>
    <FrameLayout
            android:id="@+id/base_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tl_toolbar"/>
    <include
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/tl_toolbar"
            layout="@layout/page_loading"/>

</RelativeLayout>

其中 tl_toolbar 是之前设计的标题栏布局,使用 <include> 将其添加到布局中。 page_loading 则是一个 progressBar。

重点在于 base_container 这个 FrameLayout 控件,它占据了除了标题栏之外的所有空间,因为它才是子类 Activity 布局显示的地方。

再看 BaseActivity 的代码部分:

abstract class BaseActivity : AppCompatActivity() {
    var mToolbar: Toolbar? = null;
    var toolBarTextView: TextView? = null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        setContentView(getContentViewId())
        if (getLayoutId() > 0) { // 设置界面通用布局
            mToolbar = findViewById(R.id.my_toolbar)
            layoutInflater.inflate(getLayoutId(), findViewById(R.id.base_container) as ViewGroup, true)
            initToolbar()
        }
    }



    protected fun getContentViewId(): Int {
        return R.layout.activity_base
    }

    abstract fun getLayoutId(): Int


    /**
     * 设置toolbar标题居中
     */
    fun initToolbar() {
        toolBarTextView = findViewById(R.id.toolbar_title)
        setSupportActionBar(mToolbar)
        val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(hasBackButton())
            actionBar.setDisplayShowTitleEnabled(false)
        }
    }

    /**
     * 是否有返回键
     */
    open fun hasBackButton(): Boolean {
        return true
    }


}

我们的项目是个简单的新闻应用,因此 BaseActivity 并不复杂。 首先它是个抽象类,它的抽象方法是 :

    abstract fun getLayoutId(): Int

子类必须实现它,将布局控件返回。

我们看这里:

        if (getLayoutId() > 0) { // 设置界面通用布局
            mToolbar = findViewById(R.id.my_toolbar)
            layoutInflater.inflate(getLayoutId(), findViewById(R.id.base_container) as ViewGroup, true)
            initToolbar()
        }

当子类有返回 LayoutId 的时候,就通过 layoutInflater.inflate 附加在 R.id.base_container 这个 FrameLayout 中,此时就完成将布局添加到父布局中了。

然后看 :

    fun initToolbar() {
        toolBarTextView = findViewById(R.id.toolbar_title)
        setSupportActionBar(mToolbar)
        val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(hasBackButton())    // 是否需要返回键
            actionBar.setDisplayShowTitleEnabled(false) 
        }
    }

这里就是我们设置标题栏的地方,其中我们用 hasBackButton() 控制是否要返回键,因为主页肯定是不需要的,其他页面不一定,于是就交给子类决定。其次 setDisplayShowTitleEnabled(false) 则控制着需不需要显示左侧的标题,我们已经有了居中的标题,就不需要了。

这样,我们的 BaseActivity 就设计完成了。

但是还有个小东西要弄,那就是沉浸式标题栏。

沉浸式标题栏

自从多年前,谷歌设计除了沉浸式标题栏后,就已经成为现在应用的标配了,打开 微信/QQ 都是这种样式。什么是沉浸式标题栏?如下图:

title.jpg

那么如何设置沉浸式标题栏呢?这是个简单的东西。

首先在 BaseActivity 的 setContentView 中调用 setTranslucentStatus() 方法,这时你就看到原先标题栏的黑条消失了。

    /**
     * 设置沉浸式状态栏
     */
    private fun setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val window = window
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.statusBarColor = Color.TRANSPARENT
            }
        }
    }

然而又出现一个问题,那就是标题栏陷进去了,文字没有上下居中,不好看。此时只需要在 ToolBar 控件布局中添加:

android:fitsSystemWindows="true"

即可。

此刻,基类 BaseActivity 总算设计完了,接下来的 BaseFragment 也是同样的做法,就不再多说了。

效果

写了这么多东西,怎么可以不看看效果呢?所以我们设计了一下 MainActivity ,它很简单,由一个 FrameLayout 和 BottomNavigationView 组成。

其中 FrameLayout 显示中间的内容,BottomNavigationView 就是底部的标签菜单,如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/bg_color"
            android:layout_above="@+id/nav_view"
            app:layout_constraintBottom_toTopOf="@+id/nav_view"
    />
    <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="?android:attr/windowBackground"
            app:menu="@menu/bottom_nav_menu"/>
</RelativeLayout>

BottomNavigationView 是谷歌出的一个不算新的控件了,它可以容纳 3-5 个标签并且均分。它的标签是写在 res-menu 目录下的,如下:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
            android:id="@+id/navigation_news"
            android:icon="@drawable/select_icon_news"
            android:title="@string/news_fragment"/>

    <item
            android:id="@+id/navigation_photo"
            android:icon="@drawable/select_icon_photo"
            android:title="@string/photo_fragment"/>

    <item
            android:id="@+id/navigation_video"
            android:icon="@drawable/select_icon_video"
            android:title="@string/video_fragment"/>
    <item
            android:id="@+id/navigation_about"
            android:icon="@drawable/select_icon_about"
            android:title="@string/about_fragment"/>
</menu>

至于 MainActivity 现在很简单,就是点击 BottomNavigationView 中的标签时,切换 Fragment ,全部代码如下:

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        toolBarTextView?.text="主页"
        loading.visibility = View.GONE
        val navView: BottomNavigationView = findViewById(R.id.nav_view)
        navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)


        var transaction:FragmentTransaction =supportFragmentManager.beginTransaction();
        var news = NewsFragment();
        transaction.replace(R.id.realtabcontent, news)
        transaction.commit()
    }

    override fun getLayoutId(): Int {
       return R.layout.activity_main
    }

    private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_news -> {
                var transaction:FragmentTransaction =supportFragmentManager.beginTransaction();
                var news = NewsFragment();
                transaction.replace(R.id.realtabcontent, news)
                transaction.commit()
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_photo -> {
                var transaction:FragmentTransaction =supportFragmentManager.beginTransaction();
                var photo = PhotoFragment();
                transaction.replace(R.id.realtabcontent, photo)
                transaction.commit()
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_video -> {
                var transaction:FragmentTransaction =supportFragmentManager.beginTransaction();
                var photo = VideoFragment();
                transaction.replace(R.id.realtabcontent, photo)
                transaction.commit()
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_about -> {
                var transaction:FragmentTransaction =supportFragmentManager.beginTransaction();
                var photo = AboutFragment();
                transaction.replace(R.id.realtabcontent, photo)
                transaction.commit()
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun hasBackButton(): Boolean {
        return false
    }

}

这样,就将基础框架搭建起来了,效果如下:

framework.gif

如果大家对于项目的后续感兴趣可以关注我的个人微信公众号,每次更新都会在上面进行推送,还可以加入QQ群共同进步呢

微信公众号: Android实战之旅

微信号: unidirection

扫描关注:

Android实战之旅

也可以申请加群,大家一起沟通交流

QQ 群:799054441

Android实战之旅群二维码.png

参考资料

沉浸式状态栏
https://blog.csdn.net/zephyr_g/article/details/53489320
https://blog.csdn.net/afanyusong/article/details/50915910

ActionBar 箭头颜色

https://blog.csdn.net/lovejjfg/article/details/50117543

Toolbar 使用

https://blog.csdn.net/da_caoyuan/article/details/79557704

StrictMode机制

https://duanqz.github.io/2015-11-04-StrictMode-Analysis

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,475评论 4 372
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,744评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,101评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,732评论 0 221
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,141评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,049评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,188评论 2 320
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,965评论 0 213
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,716评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,867评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,341评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,663评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,376评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,200评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,990评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,179评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,979评论 2 279