ボタンを押したら猫が移動するアニメーションをつけました。button1…上、button2…下、button3…左、button4…右にそれぞれ一定距離進みます。
実現したいことは、button5を押したら猫が初期位置に戻るようにすることです。下記コードでは、
button5.setOnClickListener以下のleftMargin、topMargin部分が赤字となりRename referenceと表示されてしまいます。
MainActivity.java
java
1package com.example.nakahara.game; 2 3import android.animation.ObjectAnimator; 4import android.os.Bundle; 5import android.support.v7.app.AppCompatActivity; 6import android.view.View; 7import android.widget.Button; 8import android.widget.ImageView; 9 10import static com.example.nakahara.game.R.id.MyCat; 11 12public class MainActivity extends AppCompatActivity { 13 final static float TRANSLATE_X = 300.0f; // 1回の操作でX軸方向にいくつ動かすか 14 final static float TRANSLATE_Y = 300.0f; // 1回の操作でY軸方向にいくつ動かすか 15 16 // 盤面上の開始座標を初期値として設定する 17 private int x = 0; 18 private int y = 0; 19 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 26 Button button1 = (Button) findViewById(R.id.button1); // うえ 27 Button button2 = (Button) findViewById(R.id.button2); // した 28 Button button3 = (Button) findViewById(R.id.button3); // ひだり 29 Button button4 = (Button) findViewById(R.id.button4); // みぎ 30 Button button5 = (Button) findViewById(R.id.button5); // やりなおし 31 32 button1.setOnClickListener(new View.OnClickListener() { 33 @Override 34 public void onClick(View v) { 35 // 「うえ」を押したときの処理 36 if (y > -3) { 37 float start = TRANSLATE_Y * y; 38 float end = start - TRANSLATE_Y; 39 animationImageView("translationY", start, end); 40 y--; 41 } 42 } 43 }); 44 button2.setOnClickListener(new View.OnClickListener() { 45 @Override 46 public void onClick(View v) { 47 // 「した」を押したときの処理 48 if (y < 0) { 49 float start = TRANSLATE_Y * y; 50 float end = start + TRANSLATE_Y; 51 animationImageView("translationY", start, end); 52 y++; 53 } 54 } 55 }); 56 button3.setOnClickListener(new View.OnClickListener() { 57 @Override 58 public void onClick(View v) { 59 // 「ひだり」を押したときの処理 60 if (x > 0) { 61 float start = TRANSLATE_X * x; 62 float end = start - TRANSLATE_X; 63 animationImageView("translationX", start, end); 64 x--; 65 } 66 } 67 }); 68 button4.setOnClickListener(new View.OnClickListener() { 69 @Override 70 public void onClick(View v) { 71 // 「みぎ」を押したときの処理 72 if (x < 2) { 73 float start = TRANSLATE_X * x; 74 float end = start + TRANSLATE_X; 75 animationImageView("translationX", start, end); 76 x++; 77 } 78 } 79 }); 80 button5.setOnClickListener(new View.OnClickListener() { 81 @Override 82 public void onClick(View v) { 83 MyCat.leftMargin = 0; 84 MyCat.topMargin = 0; 85 } 86 }); 87 } 88 void animationImageView(String property, float start, float end) { 89 ImageView imageView = (ImageView) findViewById(MyCat); 90 ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, property, start, end); 91 animator.setDuration(1000); 92 animator.start(); 93 } 94}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/30 12:22