我正在通过其适配器将按钮动态添加到网格视图中。每个按钮具有以下侦听器:
Arraylist<Button>
,在其中添加了按钮。我的getView()
方法从列表中返回适当的视图。将按预期方式处理第一个拖放事件。但是,如果我在此之后单击按钮,它们将无响应。我必须单击〜10次才能将所有10条消息都单击到控制台中。即使那样,我也无法长时间单击按钮来拖动它们。
我遵循了许多与使用ViewHolders和在getView()
的{{1}}方法中扩展视图有关的教程和许多其他建议,但实际上并不适合我,因为我从数据库接收数据。
这是我的代码段:
MainActivity.java
BaseAdapter
DragEventListener.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = findViewById(R.id.gridView);
GridAdapter adapter = new GridAdapter();
gridView.setAdapter(adapter);
for(int i = 0; i < 2; i++) {
final String text = "Hello " + (i + 1);
Button button = new Button(MainActivity.this);
button.setText(text);
adapter.addView(button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "Button " + text + " pressed");
}
});
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
View.DragShadowBuilder myShadow = new View.DragShadowBuilder(v);
v.startDrag(null, myShadow, v, 0);
return true;
}
});
button.setOnDragListener(new DragEventListener());
button.setTag("1" + i);
}
}
最后是GridAdapter.java
private class DragEventListener implements View.OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
final int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
return v instanceof Button;
case DragEvent.ACTION_DRAG_ENTERED:
v.setVisibility(View.INVISIBLE);
return true;
case DragEvent.ACTION_DRAG_LOCATION:
return true;
case DragEvent.ACTION_DRAG_EXITED:
v.setVisibility(View.VISIBLE);
return true;
case DragEvent.ACTION_DROP:
if(event.getLocalState() == v) {
return false;
}
// this is the actual view being dropped
View itemBeingDragged = (View) event.getLocalState();
GridView itemsParent = (GridView) itemBeingDragged.getParent();
GridAdapter adapter = (GridAdapter) itemsParent.getAdapter();
adapter.swap(itemBeingDragged, v);
return true;
case DragEvent.ACTION_DRAG_ENDED:
v.setVisibility(View.VISIBLE);
return true;
}
return true;
}
}
有什么想法吗?多次与public class GridAdapter extends BaseAdapter {
private volatile ArrayList<View> children = new ArrayList<>();
public void addView(View view) {
children.add(view);
notifyDataSetChanged();
}
public void swap(View v1, View v2){
int indexOfV1 = children.indexOf(v1);
int indexOfV2 = children.indexOf(v2);
Collections.swap(children, indexOfV1, indexOfV2);
notifyDataSetChanged();
}
@Override
public int getCount() {
return children.size();
}
@Override
public Object getItem(int position) {
return children.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return children.get(position);
}
}
相关的长时间点击后,我通常会得到一个异常,但是现在我无法重现该异常以显示该异常。
感谢您的帮助。