Android将图像视图移动到屏幕中心

时间:2013-05-03 06:30:18

标签: android image view translate-animation

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

my.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);

        }
    });

3 个答案:

答案 0 :(得分: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);

                }
            });

OR
修改
使用动画

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);

答案 1 :(得分:0)

点击按钮执行此操作:

LayoutParams params = (RelativeLayout.LayoutParams)imageView.getLayoutParams();
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
params.addRule(RelativeLayout.CENTER_VERTICAL);
imageView.setLayoutParams(params);

答案 2 :(得分:-1)

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

相关问题