所以我正在尝试创建一个拖放式纸牌游戏,用户必须将一堆卡片拖到相应的类别中。我想在将所有卡片拖入正确的类别后祝贺用户。
我的活动延长了View.OnLongClickListener
和View.OnDragListener
以及两个布局,topLayout
和bottomLayout
。 topLayout
是我的一堆卡片,bottomLayout
是类别部分的位置。我在bottomLayout
中有六个类别,每个类别都是FrameLayout
,并且有自己的onDragListener()
设置,如此代码所示。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLayout = (FrameLayout)findViewById(R.id.top_layout);
findViewById(R.id.cat1).setOnDragListener(this);
findViewById(R.id.cat2).setOnDragListener(this);
findViewById(R.id.cat3).setOnDragListener(this);
findViewById(R.id.cat4).setOnDragListener(this);
findViewById(R.id.cat5).setOnDragListener(this);
findViewById(R.id.cat6).setOnDragListener(this);
generateCards(); // shuffle cards and put inside topLayout()
...
}
我也为这样的类别实现onDrag()方法。这是我的问题所在。
...skipping onLongClickListener()...
@Override
public boolean onDrag(View receivingLayoutView, DragEvent dragEvent) {
ImageView draggedImage = (ImageView) dragEvent.getLocalState();
ViewGroup draggedParentLayout = (ViewGroup) draggedImage.getParent();
FrameLayout bottomLayout = (FrameLayout) receivingLayoutView;
// congratulate user when all cards dragged into correct place.
if(topLayout.getChildCount() == 0) {
victoryDialog();
}
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
if (dragEvent.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
return true;
}
return false;
...skipping other codes inside onDrag()...
}
我必须检查topLayout
是否不再有儿童观点,所以我可以祝贺用户,因为他们完成了这些卡片。问题是,因为我为六个不同的类别布局分配了听众,我的victoryDialog
会触发六次。我怎么做这个对话框只会弹出一次?我应该设置一个自定义监听器吗?
谢谢!
答案 0 :(得分:0)
我解决问题的方法(尽管我认为是一种hackish方式)只是为对话框实现Singleton pattern。在AlertDialog
类内的所有内容上声明Activity
变量。
AlertDialog singleDialog = null;
在victoryDialog()
方法内,而不是立即返回AlertDialog
我将确保通过在返回之前检查变量来检查singleDialog
的实例是否已经实例化AlertDialog
形式的singleDialog
。
private AlertDialog victoryDialog() {
if(singleDialog == null) {
return singleDialog = new AlertDialog.Builder(this)
.setTitle("Congratulations!")
.setMessage("You made it!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing here
}
}).show();
}
}
这样,类似的对话框会弹出一次,尽管由于在多个视图中分配了onDrag()
,该方法会多次触发,因为它只能通过使用此模式进行一次实例化。