我有一个带有 recyclerview 的协调器布局,我想以编程方式添加它。以编程方式添加它的原因是因为膨胀协调器布局的不同 fragment 可能使用不同类型的回收 View 。
通常对于回收 View ,为了设置此行为,我会将其添加到 xml 中:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
效果很好。但是,当我以编程方式创建回收站 View 然后将它们添加到框架布局时,我完全不知道如何添加此行为:
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/coordLayout"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:id="@+id/app_bar"
android:fitsSystemWindows="true" android:layout_height="@dimen/app_bar_height"
android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout android:id="@+id/toolbar_layout"
android:fitsSystemWindows="true" android:layout_width="match_parent"
android:layout_height="match_parent" app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
最佳答案
说明
Behavior
是CoordinatorLayout.LayoutParams
的参数。您可以使用 setBehavior
设置 CoordinatorLayout.LayoutParams
实例的行为方法。
要获得与 @string/appbar_scrolling_view_behavior
代表相同事物的正确 Behavior
对象,您应该创建 AppBarLayout.ScrollingViewBehavior
的实例.
示例
(这是我之前对原始答案的编辑的清理版本)
首先,您必须获得 CoordinatorLayout
的 child View
实例。
让我明确一点:它 不是 CoordinatorLayout
本身。 childView
是 CoordinatorLayout 的
subview 。
//e.g. like this:
val childView: View = findViewById(R.id.child_view)
假设 childView
已经附加到 CoordinatorLayout
(所以它已经有 LayoutParams
),你可以这样做:
val params: CoordinatorLayout.LayoutParams = yourView.layoutParams as CoordinatorLayout.LayoutParams
params.behavior = AppBarLayout.ScrollingViewBehavior()
yourView.requestLayout()
关于android - 设置应用程序 :layout_behavior programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707337/