Rom*_*nko 2 java android nullpointerexception android-support-library android-design-library
我正在尝试BottomSheetBehavior从Android支持设计库中实现.我初始化BottomSheetBehavior如下:
private void initBottomSheet() {
new AsyncTask<Void, Void, Void>() {
View bottomSheetFrame = rootView.findViewById(R.id.bottom_sheet);
}
@Override
protected Void doInBackground(Void... params) {
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetFrame);
bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
private boolean isOnTop = false;
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
switch (newState) {
case BottomSheetBehavior.STATE_DRAGGING: {
...
}
case BottomSheetBehavior.STATE_SETTLING: {
...
}
case BottomSheetBehavior.STATE_EXPANDED: {
...
}
case BottomSheetBehavior.STATE_COLLAPSED: {
...
}
case BottomSheetBehavior.STATE_HIDDEN: {
...
}
default: {
break;
}
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
...
});
bottomSheetBehavior.setPeekHeight((int) Utils.convertDpToPixel(100f, activityContext));
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); // NPE here
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
}
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为我可以通过Button点击或其他动作来改变状态.请帮我.
小智 6
问题
NPE的发生是因为你BottomSheetBehavior.setState(...)在观看之前打电话- bottomSheetFrame布局了.此时BottomSheetBehavior null在视图上有引用,无法将状态应用于它.
解
我通过使用View.post(Runnable)方法修复此问题:
View sheetView = ... ;
BottomSheetBehavior behavior = BottomSheetBehavior.from(sheetView);
int initState = BottomSheetBehavior.STATE_EXPANDED;
sheetView.post(new Runnable() {
@Override
public void run() {
behavior.setState(initState);
}
});
Run Code Online (Sandbox Code Playgroud)
在我的情况下,这有助于阻止NPE-s :)
| 归档时间: |
|
| 查看次数: |
1424 次 |
| 最近记录: |