ViewGroup很少会用到得东西

轻量级的移除和添加view,addView和removeView都是重量级的操作,会触发重绘,导致卡顿。

  • detachViewFromParent(View view, int index, LayoutParams params)

  • removeDetachedView(View view,boolean animate)

效果:

图片替换文本

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private fun moveToTop(target: View) {
var mViewGroup = conn
//先确定现在在哪个位置
val startIndex: Int = mViewGroup.indexOfChild(target)
//计算一共需要几次交换,就可到达最上面
val count: Int = mViewGroup.childCount - 1 - startIndex
for (i in 0 until count) {
//更新索引
val fromIndex: Int = mViewGroup.indexOfChild(target)
//目标是它的上层
val toIndex = fromIndex + 1
//获取需要交换位置的两个子View
val to: View = mViewGroup.getChildAt(toIndex)

//先把它们拿出来 这个方法是project的,所以我们需要自定义viewgroup然后重载这个方法变成public
mViewGroup.detachViewFromParent(toIndex)
mViewGroup.detachViewFromParent(fromIndex)

//再放回去,但是放回去的位置(索引)互换了
mViewGroup.attachViewToParent(to, fromIndex, to.layoutParams)
mViewGroup.attachViewToParent(target, toIndex, target.layoutParams)
}
//刷新
mViewGroup.invalidate()
}