我有一个GridView。 GridView中的每个项目都包含一些ImageView和TextView。在onLongPress()处理程序中,我在ImageView上调用startDrag。没有gridView的第一项,一切正常。我用它得到了NullPointerExpception:
E/View: Unable to initiate drag
E/View: java.lang.NullPointerException: Attempt to read from field 'android.view.IWindowSession android.view.View$AttachInfo.mSession' on a null object reference
E/View: at android.view.View.startDrag(View.java:20983)
E/View: at com.abc.xyz.util.view.CustomGridView$1.onItemLongClick(ES.java:55)
E/View: at android.widget.AbsListView.performLongPress(AbsListView.java:3939)
E/View: at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:3864)
E/View: at android.os.Handler.handleCallback(Handler.java:739)
E/View: at android.os.Handler.dispatchMessage(Handler.java:95)
E/View: at android.os.Looper.loop(Looper.java:158)
E/View: at android.app.ActivityThread.main(ActivityThread.java:7229)
E/View: at java.lang.reflect.Method.invoke(Native Method)
E/View: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
E/View: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
我能够验证传递给startDrag的所有参数都是非null - 一个ClipData,一个DragShadowBuilder,以及我作为LocalState的视图。这是代码片段:
ClipData.Item item = new ClipData.Item(((ABC) getItemAtPosition(position)).getUri());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData data = new ClipData("", mimeTypes, item);
data.addItem(new ClipData.Item(position + ""));
DragShadowBuilder shadowBuilder = new DragShadowBuilder(view.findViewById(R.id.img));
view.startDrag(data, // data to be dragged
shadowBuilder, // drag shadow
view, // local data about the drag and drop operation
0 // no needed flags
);
我发现如果在适配器中设置固定大小的GridView项,则会出现问题。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
...
v.setLayoutParams(new AbsListView.LayoutParams((int) mContext.getResources().getDimension(R.dimen.pp_item_w),
(int) mContext.getResources().getDimension(R.dimen.pp_item_h)));
return v;
}
那么,在这种情况下我可以做些什么并保持GridView项目的固定大小。
答案 0 :(得分:0)
我发现我的GridView的第一项也无法在invalidate()时更新视图。 我读了一些线程,说它可能正在发生,因为试图访问尚未膨胀的视图。 所以,我找到了我的代码的解决方案,并保持固定大小的GridView项目。仅在convertView = null时设置。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
...
if(v == null) {
...
v.setLayoutParams(new AbsListView.LayoutParams((int) mContext.getResources().getDimension(R.dimen.pp_item_w),
(int) mContext.getResources().getDimension(R.dimen.pp_item_h)));
} else {
...
}
return v;
}