0

I'm trying to make a simple animation with a image that iniatially it doesn't appear but after it appears rotating 180 degrees for certain a amount of seconds from the left of the screen. So i made a script inside the onCreate method:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView Bart = (ImageView) findViewById(R.id.bart);
        Bart.animate().translationXBy(-3000);
        Bart.animate().translationXBy(4000).rotation(180).setDuration(2000);


    }

But for some reason i'm getting an error saying that i'm trying to invoke a virtual method on a null object reference.What could be the issue?Thanks

William
  • 75
  • 1
  • 8

1 Answers1

1

You did not set setContentView() in onCreate

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main)// add this with your layout Id
    ImageView bartImageView = (ImageView) findViewById(R.id.bart);
    bartImageView.animate().translationXBy(-3000);
    bartImageView.animate().translationXBy(4000).rotation(180).setDuration(2000);


}

Also few suggestions take variables with camelCase starting with small letter . Add some identifier to the variable which indicates what it is, like bartImageView or bartIV etc.

Manohar
  • 22,116
  • 9
  • 108
  • 144
  • Hi.Thanks for answering my question.I trying to make the image disappear iniatially from the screen by doing `bartImageView.animate().translationXBy(-3000);` but it doesn't work.Do you know what it could be the problem? – William Sep 16 '20 at 13:40
  • 1
    You can hide image view by using `bartImageView.setVisibility(View.GONE)` – Manohar Sep 16 '20 at 13:43
  • I did that but i tried animating in the next line and it doesn't appear again – William Sep 16 '20 at 13:48
  • 1
    To make it visible use `bartImageView.setVisibility(View.VISIBLE)` – Manohar Sep 16 '20 at 13:57
  • Is there a way to make it go off the screen but not disappear using translationXBy?And then go back again using translationXBy?This is what i was trying to do – William Sep 16 '20 at 14:06
  • 1
    try this https://stackoverflow.com/a/59601913/6478047 – Manohar Sep 16 '20 at 14:14
  • Thanks Manohar.I find out that i wanted setX instead of translationXBy. – William Sep 17 '20 at 12:42