我在布局的顶部有一个ImageView
,在它下面有一个RecyclerView
;这就是我在自定义行为步骤1中所需要的全部内容;但是,它似乎并没有奏效。
这是代码:
的 Behavior.java
public class Depency extends CoordinatorLayout.Behavior<RecyclerView> {
private String TAG = "tag";
public Depency() {
}
public Depency(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, RecyclerView child, View
dependency) {
int delta = (int) (dependency.getTranslationY() + dependency.getBottom());
delta -= child.getTop();
child.offsetTopAndBottom(delta);
Log.i(TAG,
"onDependentViewChanged: " + delta + "," + child.getTop() + dependency.getClass().getSimpleName());
return true;
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, RecyclerView child, View dependency) {
return dependency instanceof AppCompatImageView;
}
}
layout.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.kenchan.fullypjo.MainActivity"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.AppCompatImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_girl"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.example.kenchan.fullypjo.view.Depency"/>
</android.support.design.widget.CoordinatorLayout>
但是当我在手机上运行项目时,我错了:
有人可以帮我或用我的代码告诉我吗? 这个问题困扰了我一段时间;
我试图在android.support.design.widget.AppBarLayout$ScrollingViewBehavior
中阅读源代码
我发现代码逻辑只是在不同的地方:
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child,
View dependency) {
offsetChildAsNeeded(parent, child, dependency);
return false;
}
private void offsetChildAsNeeded(CoordinatorLayout parent, View child, View dependency) {
final CoordinatorLayout.Behavior behavior =
((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior();
if (behavior instanceof Behavior) {
// Offset the child, pinning it to the bottom the header-dependency, maintaining
// any vertical gap and overlap
final Behavior ablBehavior = (Behavior) behavior;
ViewCompat.offsetTopAndBottom(child, (dependency.getBottom() - child.getTop())
+ ablBehavior.mOffsetDelta
+ getVerticalLayoutGap()
- getOverlapPixelsForOffset(dependency));
}
}
答案 0 :(得分:0)
RecyclerView
位于z-index顶部,这就是为什么您将其视为覆盖ImageView
的原因。在预览中,您只看到9个项目。
您需要在行为的RecyclerView
方法内更改onLayoutChild()
顶部,ImageView
的底部。这种方法让您有机会自己布置孩子,而不是让CoordinatorLayout
刻意去做。如果返回true,CoordinatorLayout
将不会尝试布局该视图。