【问题标题】:Translate Animation Android翻译动画安卓
【发布时间】:2016-11-13 19:57:53
【问题描述】:
我有一个 RecyclerView,里面有图片。我需要将点击的图像移动到屏幕的中心。并且不应该依赖图像的起点,它应该移动到屏幕的中心。
我尝试使用 XML 代码来执行此操作 - 它不能正常工作,TranslateAnimation 对象 - 它不能正常工作。在这两种变体中,图像的移动取决于图像的起始位置,并且所有图像的最终点都不同。
我不知道该怎么做。请帮帮我)
【问题讨论】:
标签:
android
android-studio
animation
android-recyclerview
【解决方案1】:
试试下面的代码。代码使用了Listview,但同样的逻辑可以应用到RecyclerView。
这里的方法是在列表视图的父布局中创建一个新的图像视图,与单击的图像重叠。然后将新创建的 imageview 平移到屏幕中心。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = (RelativeLayout) findViewById(R.id.main_root);
listView = (ListView) findViewById(R.id.list);
MyAdapter adapter = new MyAdapter(MainActivity.this, web, imageId);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView imgView = (ImageView) view.findViewById(R.id.grid_image);
// Get location of window with respect to window.
int location[] = new int[2];
imgView.getLocationInWindow(location);
// Create a new image view overlapping
// the image view that was clicked.
ImageView imgView2 = new ImageView(MainActivity.this);
imgView2.setImageDrawable(imgView.getDrawable());
// To make it overlap, use the location values of
// the clicked image as left and top margin for the
// new image.
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
imgView.getWidth(), imgView.getHeight());
params.leftMargin = location[0];
params.topMargin = location[1] - getStatusBarHeight();
// Add the new image view to the root view of the activity.
root.addView(imgView2, params);
translateToCenter(imgView2, location);
}
});
}
/**
* To translate the new image view to the center of the screen.
* @param view
* @param originalLoc
*/
private void translateToCenter(View view , int originalLoc[])
{
int xMove = root.getWidth() / 2 - view.getWidth() / 2 - originalLoc[0];
int yMove = root.getHeight() / 2 - view.getHeight() / 2 - originalLoc[1];
TranslateAnimation anim = new TranslateAnimation( 0, xMove , 0, yMove );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
/**
* To get the status bar height.
* @return
*/
private int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier(
"status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}