Android bringToFront在RecyclerView中不起作用
我想在Android bringToFront在RecyclerView中不起作用,android,android-layout,android-recyclerview,Android,Android Layout,Android Recyclerview,我想在RecyclerView中制作一个动画,它要求一个孩子的z索引比另一个孩子的大。但是,当我在ViewGroup中使用bringToFront方法时,它不起作用 是否有任何方法可以在回收视图中将孩子带到前面?孩子的顺序由LayoutManager控制。出于性能原因,内置布局管理器有自己严格的子顺序 当前的实现只是将子项移动到子项列表的末尾,这对现有的LayoutManager不起作用 若你们的目标是棒棒糖,你们可以使用这种方法。 要针对较旧的平台,您需要一个不依赖于子级顺序的自定义Layou
RecyclerView
中制作一个动画,它要求一个孩子的z索引比另一个孩子的大。但是,当我在ViewGroup
中使用bringToFront
方法时,它不起作用
是否有任何方法可以在
回收视图
中将孩子带到前面?孩子的顺序由LayoutManager控制。出于性能原因,内置布局管理器有自己严格的子顺序
当前的实现只是将子项移动到子项列表的末尾,这对现有的LayoutManager不起作用
若你们的目标是棒棒糖,你们可以使用这种方法。
要针对较旧的平台,您需要一个不依赖于子级顺序的自定义LayoutManager。事实上,bringToFront()
没有帮助;它只更改其父级的子级数组中子级的顺序,但不更改子级的渲染顺序
如果您使用的是API-21或更高版本,您只需更改视图的Z
值(view.setZ(…)
)即可将其置于最前面
API-21下面有一个回调函数,您可以使用:RecyclerView.ChildDrawingOrderCallback
。使用它,您可以定义子对象的呈现顺序。(如果您不喜欢通过更改Z
值而获得的额外阴影,也可以将其与API-21+一起使用。)
例如:
final int indexOfFrontChild = rv.indexOfChild(desiredFrontView);
rv.setChildDrawingOrderCallback(new RecyclerView.ChildDrawingOrderCallback() {
private int nextChildIndexToRender;
@Override
public int onGetChildDrawingOrder(int childCount, int iteration) {
if (iteration == childCount - 1) {
// in the last iteration return the index of the child
// we want to bring to front (and reset nextChildIndexToRender)
nextChildIndexToRender = 0;
return indexOfFrontChild;
} else {
if (nextChildIndexToRender == indexOfFrontChild) {
// skip this index; we will render it during last iteration
nextChildIndexToRender++;
}
return nextChildIndexToRender++;
}
}
});
rv.invalidate();
基本上,
onGetChildDrawingOrder(…)
将被调用childCount
次,在每次迭代中我们可以指定渲染哪个子级(通过返回其索引)。以上@Zsolt Safrany的回答是基于这样一个假设,即回调总是从迭代0调用的,而我测试的结果是不正确的
在这里,我发布的工作实现,不依赖于外部计数器
//index of item you want to be displayed on top
private int indexOfFrontChild = 2;
@Override
public int onGetChildDrawingOrder(int childCount, int iteration) {
int childPos = iteration;
//index must be in at least smaller than all children's
if (indexOfFrontChild < childCount) {
//in the last iteration we return view we want to have on top
if (iteration == childCount - 1) {
childPos = indexOfFrontChild;
}else if (iteration >= indexOfFrontChild) {
childPos = iteration + 1;
}
}
return childPos;
}
//要显示在顶部的项目索引
private int indexOfFrontChild=2;
@凌驾
公共int onGetChildDrawingOrder(int子计数,int迭代){
int childPos=迭代;
//索引必须至少小于所有子级的
if(indexOfFrontChild=indexOfFrontChild){
childPos=迭代+1;
}
}
返回childPos;
}
在我的例子中,项目可以改变它们的高度,这样一个项目就可以占据整个屏幕。因此,检查indexOfFrontChild项是否可显示很好
if (indexOfFrontChild < childCount)
if(indexOfFrontChild
谢谢,但是自定义LayoutManager可能会增加一些复杂性,我尝试了一些技巧来克隆我想要制作动画的视图。对这个5年前的答案进行了一些更新:RecyclerView现在提供了一个API,可以使用setChildDrawingOrderCallback()覆盖绘图顺序。
。尝试了以下代码。在尝试滚动RecyclerView时使用应用程序会导致应用程序崩溃。@0101100101,您确定您的indexOfFrontChild在[0,childCount-1]范围内吗?或者换一种说法,你确定你的desiredFrontView是你的RecyclerView的孩子吗?都是。动画实际上与该代码配合得很好,只有在不配合后才能滚动。@AlexNewman,这取决于onGetChildDrawingOrder()的价格。上述实现非常便宜。