我有一个对话框菜单设置供用户选择他们想要构建的建筑物。当他们按下购买按钮时,建筑物会自动插入活动中。问题在于,当购买不止一个时,移动最近购买的建筑也将搬迁最近购买的第二栋建筑。我不肯定如何解决这个问题。我会看到如果将新建筑物设置为框架布局而不是线性布局会有所帮助,但如果我这样做的话,我的拖放工作就不起作用了。
以下是按下购买按钮后设置的图像按钮的代码:
layout = (LinearLayout) findViewById(R.id.newColonyHutLayout);
buyColonyHut = (Button) buildingSelect.findViewById(R.id.buyColonyHut);
buyColonyHut.setText("Buy");
buyColonyHut.setBackgroundColor(-65536);
buyColonyHut.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//get current amount of rock and check if it is enough to buy
data = new Database(runGraphics.this);
data.open();
rockAmount = data.getRockAmount();
data.close();
if (rockAmount >= 100)
{
//take away spent money and update database
data.open();
rockAmount -= 100;
data.rockAmountEntry(rockAmount);
data.close();
//update the scores
updateScores();
//close the dialog
buildingSelect.dismiss();
buildMoreButton.setBackgroundColor(-65536);
//they have enough rock, build the building
newColonyHut = new ImageButton(runGraphics.this);
newColonyHut.setBackgroundResource(R.drawable.mainhut);
newColonyHut.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(newColonyHut);
newColonyHut.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
newColonyHutSelected = true;
}//end if
if (event.getAction() == MotionEvent.ACTION_UP)
{
if (newColonyHutSelected == true)
{
newColonyHutSelected = false;
}//end if
}//end if
else if (event.getAction() == MotionEvent.ACTION_MOVE)
{
if (newColonyHutSelected == true)
{
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(v.getWidth(), v.getHeight());
params.setMargins((int)(event.getRawX() - event.getRawY() / 5), (int) (event.getRawY() - v.getHeight()), (int) (event.getRawX() - v.getWidth() / 5), (int) (event.getRawY() - v.getHeight()));
v.setLayoutParams(params);
}//end if
}//end else
return false;
}//end onTouch function
});//end setOnTouchListener
}//end onClick function
});//end onClickListener
这是xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/newColonyHutLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageButton
android:id="@+id/newColonyHut"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/mainhut" />
</LinearLayout>
</FrameLayout>
答案 0 :(得分:0)
尝试在true
方法的末尾返回onTouch()
,以通知侦听器已使用TouchEvent。否则将调用被触摸的View下面的View的后续监听器 - 例如你的第二座建筑之一。
另一个想法是使用View.onDragListener
,而不是完全自行实现拖放。以下是如何使用它的一个很好的示例:http://www.vogella.com/tutorials/AndroidDragAndDrop/article.html#draganddrop_overview