繁体   English   中英

创建一个拖放ImageButton

[英]Creating a Drag and Drop ImageButton

我看过有关如何使我的imagebutton能够拖放的教程。 有了代码,当我单击图像按钮时,它就会消失。 当我单击其他任何地方时,它不会再出现。

这是我的imagebutton代码:

    mainHut = (ImageButton) findViewById(R.id.mainHut);
    mainHut.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event) 
        {
            Toast.makeText(getApplicationContext(), "in the movement", Toast.LENGTH_SHORT).show();
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                mainHutSelected = true;
            }//end if

            if (event.getAction() == MotionEvent.ACTION_UP)
            {
                if (mainHutSelected == true)
                {
                    mainHutSelected = false;
                }//end if
            }//end if
            else if (event.getAction() == MotionEvent.ACTION_MOVE)
            {
                if (mainHutSelected == true)
                {
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 50);
                    params.setMargins((int)event.getRawX() - 25, (int) event.getRawY() - 50, 0, 0);
                    layout = (LinearLayout) findViewById(R.id.gllayout);
                    layout.removeView(mainHut);
                    layout.addView(mainHut, params);
                }//end if
            }//end else

            return false;
        }//end onTouch function

    });

这是布局的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gllayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@drawable/bgm" >

        <ImageButton
            android:id="@+id/mainHut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/mainhut" />
</LinearLayout>

任何帮助表示赞赏。 谢谢。

要回答我自己的问题...这就是我解决问题的方式。 我花了很长时间才弄清楚这一点,但事实确实如此。 当涉及到我自己的imagebutton时,参数有些混乱,因此我将必须弄清楚该用什么来将手指保持在按钮的中央,但这就像我想要的那样移动按钮:

button.setOnTouchListener(new View.OnTouchListener() 
{

    public boolean onTouch(View v, MotionEvent event)
    {
        if (me.getAction() == MotionEvent.ACTION_MOVE )
        {
             LayoutParams params = new LayoutParams(v.getWidth(),  v.getHeight());
             params.setMargins((int)event.getRawX() - v.getWidth()/2, (int)(event.getRawY() - v.getHeight()), (int)event.getRawX() - v.getWidth()/2, (int)(event.getRawY() - v.getHeight()));
             v.setLayoutParams(params);
        }
        return false;
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM