android– 使用AppCompat BottomSheets的NullPointerException

android– 使用AppCompat BottomSheets的NullPointerException,第1张

概述LinearLayoutbottomSheetViewgroup=(LinearLayout)findViewById(R.id.bottomSheet);bottomSheetBehavior=BottomSheetBehavior.from(bottomSheetViewgroup);bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);/hisline我在我的activity的onCreat

linearLayout bottomSheetVIEwgroup = (linearLayout) findVIEwByID(R.ID.bottomSheet);bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetVIEwgroup);bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); //this line

我在我的activity的onCreate()方法中有这个代码,当执行最后一行时,我得到了下面的NPE异常:

Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method ‘java.lang.Object java.lang.ref.WeakReference.get()’ on a null object reference
at androID.support.design.Widget.BottomSheetBehavior.setState(BottomSheetBehavior.java:440)

解决方法:

虽然Sanf0rds的答案是正确的,但它不允许将BottomSheet定义为默认展开.问题是由于onLayoutChild的最后一行未设置WeakReference引起的.

解决方案是提供我们自己的类,它扩展了BottomSheetBehavior,但是在重写的onLayoutChild中设置状态.代码如下.

英国/ AC / QUB / quibe /其它/ ExpandedBottomSheetBehavior.java

package uk.ac.qub.quibe.misc;import androID.content.Context;import androID.support.design.Widget.CoordinatorLayout;import androID.util.AttributeSet;import androID.vIEw.VIEw;/** * Created by mcp on 15/03/16. */public class ExpandedBottomSheetBehavior<V extends VIEw> extends androID.support.design.Widget.BottomSheetBehavior<V> {    public ExpandedBottomSheetBehavior(Context context, AttributeSet attrs) {        super(context, attrs);    }    @OverrIDe    public boolean onLayoutChild(final CoordinatorLayout parent, final V child, final int layoutDirection) {        SavedState dummySavedState = new SavedState(super.onSaveInstanceState(parent, child), STATE_EXPANDED);        super.onRestoreInstanceState(parent, child, dummySavedState);        return super.onLayoutChild(parent, child, layoutDirection);        /*            Unfortunately its not good enough to just call setState(STATE_EXPANDED); after super.onLayoutChild            The reason is that an animation plays after calling setState. This can cause some graphical issues with other layouts            Instead we need to use setInternalState, however this is a private method.            The trick is to utilise onRestoreInstance to call setInternalState immediately and indirectly         */    }}

在布局文件引用中引用您的新自定义行为.

更改

app:layout_behavior="androID.support.design.Widget.BottomSheetBehavior"

app:layout_behavior="uk.ac.qub.quibe.misc.ExpandedBottomSheetBehavior"
总结

以上是内存溢出为你收集整理的android – 使用AppCompat BottomSheets的NullPointerException全部内容,希望文章能够帮你解决android – 使用AppCompat BottomSheets的NullPointerException所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1099563.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存