所以我创建了一个扩展 View 的自定义类。 我在这个类中的 onDraw() 如下:
@Override
protected void onDraw(Canvas canvas) {
Bitmap myBitmap = BitmapFactory.decodeResource (getResources(), R.drawable.image);
super.onDraw(canvas);
final Paint paint = new Paint();
paint.setTextSize(100);
paint.setColor(Color.BLUE);
canvas.drawBitmap(myBitmap, 10, 10, paint);
canvas.drawText(date, 200, 200, paint);
invalidate();
}
主要 Activity :
public class MainActivity extends AppCompatActivity{
private Button animateBtn;
private ImageView image;
private Animation anim;
private Calendar calendar;
private Customclass cc;
private Animation animation;
@Override
protected void onCreate(Bundle savedInstanceState) {
cc = new Customclass(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayShowHomeEnabled(true);
actionbar.setIcon(R.mipmap.launcher_icon);
// Create the view and add it to the layout
RelativeLayout rl = (RelativeLayout) findViewById(R.id.myLayout);
rl.addView(cc);
}
public void startAnim(View v){
Customclass customclass = (Customclass ) findViewById(R.id.custom_view);
Animation animation = AnimationUtils.loadAnimation(this,R.anim.rotation);
customclass.startAnimation(animation); //<- crashes here!
}
}
最后是旋转 xml:
<?xml version="1.0" encoding="utf-8"?>
<rotate android:pivotY="50%"
android:pivotX="50%"
android:toDegrees="1080"
android:fromDegrees="0"
android:duration="3000"
xmlns:android="http://schemas.android.com/apk/res/android">
</rotate>
我只是添加一个位图和一些文本。我在主要 Activity 中想要做的是通过单击一次按钮在一个动画中旋转整个 CustomView 但我无法让它工作! 我已经尝试了几种动画解决方案,但每当我启动动画时,我总是会崩溃。
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.lab3.Customclass .startAnimation(android.view.animation.Animation)' on a null object reference
非常感谢任何帮助!
最佳答案
有一个简单的解决方案。单击按钮即可启动动画,如下所示。只需将 view 替换为您的 View 名称即可。
view.animate().rotation(360).setDuration(1000);
关于java - 使用按钮 onClick() 为自定义 View 添加动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006158/