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

Android将图像视图移动到屏幕中央,android,image,view,translate-animation,Android,Image,View,Translate Animation,我在屏幕底部有一个按钮和一个图像视图。单击按钮时,我想将图像视图移动到屏幕的中心。我正在尝试以下代码。我说得不对。请帮帮我 my.java文件 button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub imagev

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

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

        }
    });

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

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

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

没有动画


编辑
生气勃勃


为什么它不随翻译动画一起移动?在.xml文件中使用哪种布局?(相对或线性)感谢大家的回复。如何使用平移动画将图像视图移动到中心。?
 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);