我使用 Android设计库创建了一个应用,其中包含工具栏和TabLayout。
实际上有两个标签,都有2个RecyclerView,滚动时会自动折叠工具栏。
我的问题是:当RecyclerView包含少量项目且完全适合屏幕时(如TAB 2中),我可以禁用工具栏折叠吗?
我已经看到很多像CheeseSquare这样的例子,由Google员工提出问题仍然存在:即使RecyclerView只有1个项目,工具栏仍会隐藏在滚动状态。
我想我可以找出是否在屏幕上显示RecyclerView的第一项,如果是,则禁用工具栏折叠。前者易于实现,后者又如何呢?
这是我的布局:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/glucosio_pink"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorColor="@color/glucosio_accent"
app:tabTextColor="#80ffffff"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_fab"
android:layout_margin="16dp"
android:onClick="onFabClicked"
app:backgroundTint="@color/glucosio_accent"
android:src="@drawable/ic_add_black_24dp"
android:layout_gravity="bottom|right"
/>
</android.support.design.widget.CoordinatorLayout>
答案 0 :(得分:26)
最终解决方案(感谢MichałZ。)
关闭/打开工具栏滚动的方法:
public void turnOffToolbarScrolling() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
//turn off scrolling
AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
toolbarLayoutParams.setScrollFlags(0);
mToolbar.setLayoutParams(toolbarLayoutParams);
CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(null);
appBarLayout.setLayoutParams(appBarLayoutParams);
}
public void turnOnToolbarScrolling() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
//turn on scrolling
AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
mToolbar.setLayoutParams(toolbarLayoutParams);
CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
appBarLayout.setLayoutParams(appBarLayoutParams);
}
找出我的片段中是否可以看到RecyclerView的最后一项
如果是,请禁用滚动:
public void updateToolbarBehaviour(){
if (mLayoutManager.findLastCompletelyVisibleItemPosition() == items.size()-1) {
((MainActivity) getActivity()).turnOffToolbarScrolling();
} else {
((MainActivity)getActivity()).turnOnToolbarScrolling();
}
}
答案 1 :(得分:8)
RecyclerView
现在(自版本23.2起)支持wrap_content
。只需使用wrap_content
作为高度。
答案 2 :(得分:4)
我采用了一种稍微不同的方法来解决这个问题。
我创建了一个自定义AppBarBehavior,根据单元格禁用其自我。
public class CustomAppBarBehavior extends AppBarLayout.Behavior {
private RecyclerView recyclerView;
private boolean enabled;
public CustomAppBarBehavior() {
}
public CustomAppBarBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
updatedEnabled();
return enabled && super.onInterceptTouchEvent(parent, child, ev);
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes) {
return enabled && super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes);
}
@Override
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
return enabled && super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
}
private void updatedEnabled() {
enabled = false;
if(recyclerView != null) {
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (adapter != null) {
int count = adapter.getItemCount();
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager != null) {
int lastItem = 0;
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
lastItem = Math.abs(linearLayoutManager.findLastCompletelyVisibleItemPosition());
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
int[] lastItems = staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
lastItem = Math.abs(lastItems[lastItems.length - 1]);
}
enabled = lastItem < count - 1;
}
}
}
}
public void setRecyclerView(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
}
然后在应用栏布局
上设置自定义行为appBarBehavior = new CustomAppBarBehavior();
CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
appBarLayoutParams.setBehavior(appBarBehavior);
appBarLayout.setLayoutParams(appBarLayoutParams);
最后页面更改视图寻呼机更新了RecyclerView的行为
private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
@Override
public void onPageSelected(final int position) {
appBarLayout.setExpanded(true, true);
appBarLayout.post(new Runnable() {
@Override
public void run() {
appBarBehavior.setRecyclerView(childFragments.get(position).getRecyclerView());
}
});
}
@Override
public void onPageScrollStateChanged(int state) { }
};
这应该适用于更改数据集。
答案 3 :(得分:1)
在适配器中更改数据后添加以下代码:
recyclerView.afterMeasured {
val isTurnedOff = recyclerView.turnOffNestedScrollingIfEnoughItems()
if (isTurnedOff) appBarLayout.setExpanded(true)
}
这是功能:
inline fun <T: View> T.afterMeasured(crossinline action: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
action()
}
})
}
fun RecyclerView.turnOffNestedScrollingIfEnoughItems(): Boolean {
val lm = (layoutManager as LinearLayoutManager)
val count = if (lm.itemCount <= 0) 0 else lm.itemCount - 1
val isFirstVisible = lm.findFirstCompletelyVisibleItemPosition() == 0
val isLastItemVisible = lm.findLastCompletelyVisibleItemPosition() == count
isNestedScrollingEnabled = !(isLastItemVisible && isFirstVisible)
return isNestedScrollingEnabled.not()
}
答案 4 :(得分:1)
我想这是最好的解决方案。 您需要定义自定义AppBarLayout行为:
class CustomScrollingViewBehavior : AppBarLayout.Behavior {
constructor() : super()
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
var shouldScroll = true
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: AppBarLayout, directTargetChild: View, target: View, axes: Int, type: Int): Boolean {
return shouldScroll && when (target) {
is NestedScrollView, is ScrollView, is RecyclerView -> {
return target.canScrollVertically(1) || target.canScrollVertically(-1)
}
else -> super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type)
}
}
}
然后您只需要在布局中将其用作AppBarLayout的属性即可
...
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="56dp"
app:layout_behavior=".CustomScrollingViewBehavior">
...
就是这样。
注意:自定义行为还支持完全禁用滚动-您只需要将shouldScroll标志设置为false
customScrollingViewBehavior.shouldScroll = false
答案 5 :(得分:0)
如果根据正确答案帮助Kotlin中的任何人,我都会为Kotlin做到这一点:
fun changeToolbarScroll(isToScrolling: Boolean){
val params = toolbar.layoutParams as AppBarLayout.LayoutParams
val appBarLayoutParams = appBarLayout.layoutParams as
CoordinatorLayout.LayoutParams
params.scrollFlags = 0
toolbar.layoutParams = params
appBarLayoutParams.behavior = null
appBarLayout.layoutParams = appBarLayoutParams
if(isToScrolling){
params.scrollFlags =
AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or
AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
toolbar.layoutParams = params
appBarLayoutParams.behavior = AppBarLayout.Behavior()
appBarLayout.layoutParams = appBarLayoutParams
}
}
就我而言,我遇到了一个MainActivity问题,该问题按2个片段管理导航,工具栏和其他共享的东西,第一个Framgent使用RecyclerView,第二个用于显示数据。 问题是当我设置菜单并从MainAcitivity更改MenuItem时
听起来听起来很愚蠢而且完全合乎逻辑,但是请记住在更改片段不起作用或无法正确更新的情况下,始终在致电supportFragmentManager.beginTransaction()之前对Menu或MenuItem进行更改.add,.replace(),show()...
fun showDetailImageFragment(searchImage: SearchImage) {
val searchFragment =
supportFragmentManager.findFragmentByTag(SEARCH_IMAGES)
changeToolbarScroll(false)
if (supportActionBar != null) {
supportActionBar!!.collapseActionView()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.title = getString(R.string.detail_image_title)
}
actionSearch.isVisible = false
actionNighMOde.isVisible = false
actionAppSetings.isVisible = false
actionAbout.isVisible = false
supportFragmentManager.beginTransaction()
.setCustomAnimations(
R.animator.fade_in,
R.animator.fade_out,
R.animator.fade_in,
R.animator.fade_out
)
.hide(searchFragment!!)
.add(
R.id.frameLayout,
DetailImageFragment().newInstance(searchImage)
).addToBackStack(null)
.commit()
}
答案 6 :(得分:-1)
您可以通过以下方式在XML中添加值为layout_behaviour
的属性@string/appbar_scrolling_view_behavior
:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
答案 7 :(得分:-2)
//turn off scrolling
AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
toolbarLayoutParams.setScrollFlags(0);
mToolbar.setLayoutParams(toolbarLayoutParams);
答案 8 :(得分:-2)
只需从
中删除滚动条app:layout_scrollFlags="scroll|enterAlways"
所以它应该是
app:layout_scrollFlags="enterAlways"