拖放问题

时间:2014-09-24 16:12:14

标签: android drag-and-drop

我正在开发一个Android应用程序,用户只需在屏幕上自由拖动一个图标,但是,当我将我的图标(imageview)拖到底部或右边时,它会越来越小当我拖动(从底部或向右)时,它会变小..

每当我将它拖到屏幕的任何地方时,我都想保持我的图标大小。

请帮忙。我现在要解决这个问题好几天了。谢谢。

    public class MainActivity extends Activity {

int windowwidth;
int windowheight;
ImageView ce;

private android.widget.RelativeLayout.LayoutParams layoutParams ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    windowwidth = getWindowManager().getDefaultDisplay().getWidth();
    windowheight = getWindowManager().getDefaultDisplay().getHeight();

    System.out.println("width" +windowwidth);
    System.out.println("height" +windowheight);

    ce = (ImageView)findViewById(R.id.imagecenter);
    ce.setOnTouchListener(new View.OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            layoutParams = (RelativeLayout.LayoutParams) ce.getLayoutParams();

            switch(event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    break;

                case MotionEvent.ACTION_MOVE:
                    int x_cord = (int) event.getRawX();
                    int y_cord = (int) event.getRawY();

                    System.out.println("value of x" +x_cord);
                    System.out.println("value of y" +y_cord);

                    if (x_cord > windowwidth) {
                        x_cord = windowwidth;
                    }
                    if (y_cord > windowheight) {
                        y_cord = windowheight;
                    }
                    layoutParams.leftMargin = x_cord-25;
                    layoutParams.topMargin = y_cord-25;
                    ce.setLayoutParams(layoutParams);
                    break;
                default: break;
            }
            return true;
        }
    });
} }

XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg2"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ImageView
    android:id="@+id/imagecenter"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:src="@drawable/imagec" /></RelativeLayout>

0 个答案:

没有答案