我遇到了ImageView
之一的动作问题。更具体地说,我需要它向下移动屏幕,然后以某种方式在顶部备份,以便它可以再次下降。
void settingCage1(){
Random X = new Random();
int xx = X.nextInt(30)+1; //this is to set Random location of cage on X axis
final ImageView cage = (ImageView)findViewById(R.id.cage1);
DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
float dpHeight = dm.heightPixels;// / dm.density;
float dpWidth = dm.widthPixels;// / dm.density;
int wid2;
int het2;
het2 = (int) ((dpHeight*0.16));
wid2 = (int) ((dpWidth*0.16));
cage.setMaxHeight(het2);
cage.setMaxWidth(wid2);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) cage.getLayoutParams();
RelativeLayout.LayoutParams llp = (RelativeLayout.LayoutParams) cage.getLayoutParams();
lp.leftMargin = (int) ((dpWidth * (50)/100)); //setting the location of Cage anywhere on the left half of the screen
llp.bottomMargin = (int) ((dpHeight * 0.626)); //this is where it will be falling to
lp.topMargin = RelativeLayout.ALIGN_PARENT_TOP; //this is the cage's starting pos.
cage.layout(lp.leftMargin, RelativeLayout.ALIGN_PARENT_START, 0, 0);
cage.animate().translationY(llp.bottomMargin).setDuration(4000); //this moves the cage to the desired area and a reasonable duration.
}
此代码到目前为止有效!然而,它只做了一半的工作,我需要它回到顶部,并不断下降。我试过这个方法:
for (int i =0; i<6; i++) {
cage.layout(lp.leftMargin, RelativeLayout.ALIGN_PARENT_START, 0, 0);
cage.animate().translationY(llp.bottomMargin).setDuration(4000);
cage.setVisibility(View.GONE);
cage.animate().translationY(lp.topMargin);
cage.setVisibility(View.VISIBLE);
}
然而,这不起作用,并且笼子设置在一个位置而不移动。
以下是笼子和父亲的XML
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0px"
android:paddingLeft="0px"
android:paddingRight="0px"
android:paddingTop="0px"
tools:context="com.Cage.Game"
android:id="@+id/prnt">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="50dp"
android:minHeight="50dp"
android:src="@drawable/cageday"
android:adjustViewBounds="true"
android:id="@+id/cage1"/>
</RelativeLayout>