2013-05-03 70 views
-1

我在屏幕底部有一个按钮和一个图像视图。当点击按钮时,我想将图像视图移动到屏幕中央。我试着用下面的代码。我没有得到正确的。请帮帮我。Android移动图像视图到屏幕中心

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

     } 
    }); 
+0

为.xml文件,该文件的布局使用?(相对或线性) – AnilPatel 2013-05-03 06:57:49

回答

0

做这个按钮点击:

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

它为什么不移动翻译动画? – Balaji 2013-05-03 06:39:50

-1

您的布局文件中的代码将是更好的调试。无论如何,我假设你正在使用相对Laytout作为父按钮和图像,因为它会更容易做到这一点。

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

谢谢大家的回复。如何将图像视图移动到翻译动画的中心? – Balaji 2013-05-03 07:39:53

+0

取决于你的逻辑。 – AnilPatel 2013-05-03 08:28:59

相关问题