LoginSignup
1
0

More than 3 years have passed since last update.

AndroidのBottomNavigationViewの上にインジケータを楽に取り付け

Last updated at Posted at 2019-10-01

やぁおはこんばんにちわ。
元気ですか?
いつもスッキリさせるものを紹介するんですが、今日もその類です。

6行程度の実装とレイアウトに少し変更を加えるだけで簡単に実装できるのでメモがてら共有ってかんじですね。
フルソースコードはこちら(Github) におきました。

まず動作を録画してGitアニメーションつくったのでみてください。

ezgif.com-video-to-gif (2).gif

どうやったかというとLinearLayout(Vertical)内のViewのWeightをコードからいじることでアニメーションさせるトリックをつかいました。
Kotlinのコードはこちら

    fun changeBottomNavProgress(index: Int) {
        if (index < 0) return
        val progress = (index) * 33f
        with(bottomNavProgressLeftPaddingView) {
            val lp = layoutParams as LinearLayout.LayoutParams
            lp.weight = progress
            layoutParams = lp
            (this.parent as ViewGroup).layoutTransition.enableTransitionType(android.animation.LayoutTransition.CHANGING)
        }
    }

差し込んだレイアウト側はこんな感じ

    <LinearLayout
        android:id="@+id/progressbar"
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:animateLayoutChanges="true"
        android:orientation="horizontal"
        android:weightSum="99"
        android:background="@android:color/darker_gray"
        android:layout_marginBottom="?attr/actionBarSize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <View
            android:id="@+id/weight_progress_left_padding"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="33"
            android:background="@color/design_default_color_primary" />

    </LinearLayout>

動作はweight_progress_left_paddingのweightを0にしたり33にしたり66にしたりすると、隣にある青い色のViewが動いているように見えるようにつくってます。知ってみれば簡単なことですね。簡単だしシンプルだし。

android:weightSum="99"としてやるのが結構ミソです。まぁ3にしてval progress = (index)にしてもいいんですが・・・そこはご愛嬌です。レビューでは3にしろって言われるでしょうねw

アニメーションさせるにはKotlinコード側で(this.parent as ViewGroup).layoutTransition.enableTransitionType(android.animation.LayoutTransition.CHANGING)をsetLayout前後で書いてやる必要があります。
あとレイアウトXML側にもandroid:animateLayoutChanges="true"をつけてやらないと実行時に例外でコケます。

いやぁシンプルでいいですね。これでスッキリかけます。楽したい人はどうぞ。

(ちょっとレイアウトに差し込むのが面倒だったので、みんなも頑張って。リンクにおいたソースコードのやつ使えばいけそうだけどね!)

おまけ

プログレスバーの擬似実装もやってみました。コードは増えますがとてもシンプルなコードです!
ezgif.com-video-to-gif (1).gif

コードは上で紹介したリンクみてやってください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0