-1

我的屏幕底部有一个按钮和一个图像视图。单击按钮时,我想将图像视图移动到屏幕中央。我正在尝试使用以下代码。我没有正确。请帮我。

我的.java 文件

      button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            imageview= (ImageView)findViewById(R.id.imageView1);
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);

        float   x=metrics.heightPixels/2;
        float   y=metrics.widthPixels/2;
         TranslateAnimation anim = new TranslateAnimation( 0, x , 0, y);
         anim.setDuration(1000);
         anim.setFillAfter( true );
          imageview.startAnimation(anim);

        }
    });
4

3 回答 3

4

没有动画

 button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    RelativeLayout.LayoutParams parms2 = new RelativeLayout.LayoutParams(width,height);
                     parms2.addRule(RelativeLayout.CENTER_VERTICAL);
                     parms2.addRule(RelativeLayout.CENTER_HORIZONTAL);
                      imageview.setLayoutParams(parms2);

                }
            });

用动画
编辑

RelativeLayout root = (RelativeLayout) findViewById( R.id.rl1 );
                DisplayMetrics dm = new DisplayMetrics();
               // this.getWindowManager().getDefaultDisplay().getMetrics( dm );
                getWindowManager().getDefaultDisplay().getMetrics(dm);
                int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

                int originalPos[] = new int[2];
                imageview.getLocationOnScreen( originalPos );

                int xDest = dm.widthPixels/2;
                xDest -= (img.getMeasuredWidth()/2);
                int yDest = dm.heightPixels/2 - (imageview.getMeasuredHeight()/2) - statusBarOffset;

                TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
                anim.setDuration(1000);
                anim.setFillAfter( true );
                imageview.startAnimation(anim);
于 2013-05-03T07:00:16.490 回答
0

在按钮单击时执行此操作:

LayoutParams params = (RelativeLayout.LayoutParams)imageView.getLayoutParams();
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.CENTER_VERTICAL);
imageView.setLayoutParams(params);
于 2013-05-03T06:36:01.053 回答
-1

您的布局文件代码会更好地调试。无论如何,我假设您使用相对布局作为按钮和图像的父级,因为这样做会更容易。

于 2013-05-03T06:49:45.440 回答