1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.deskclock
17 
18 import android.content.Context
19 import android.util.AttributeSet
20 import android.view.MotionEvent
21 import androidx.recyclerview.widget.RecyclerView
22 
23 /**
24  * Thin wrapper around RecyclerView to prevent simultaneous layout passes, particularly during
25  * animations.
26  */
27 class AlarmRecyclerView @JvmOverloads constructor(
28     context: Context,
29     attrs: AttributeSet? = null,
30     defStyle: Int = 0
31 ) : RecyclerView(context, attrs, defStyle) {
32     private var mIgnoreRequestLayout = false
33 
34     init {
35         addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
onInterceptTouchEventnull36             override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
37                 // Disable scrolling/user action to prevent choppy animations.
38                 return rv.getItemAnimator()!!.isRunning()
39             }
40         })
41     }
42 
onLayoutnull43     override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
44         mIgnoreRequestLayout = true
45         super.onLayout(changed, left, top, right, bottom)
46         mIgnoreRequestLayout = false
47     }
48 
requestLayoutnull49     override fun requestLayout() {
50         if (!mIgnoreRequestLayout &&
51                 (getItemAnimator() == null || !getItemAnimator()!!.isRunning())) {
52             super.requestLayout()
53         }
54     }
55 }