A.J. A.J. - 3 months ago 4
Java Question

Error when writing the method of a button

I have a button which I want to move when it is clicked.
Why does this code give me error?

"setOnClickListener" is red just like "view"

import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {

ImageButton play = (ImageButton) findViewById(R.id.play);
ImageButton score = (ImageButton) findViewById(R.id.score);
ImageButton options = (ImageButton) findViewById(R.id.options);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}

play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

TranslateAnimation translateAnimation = new TranslateAnimation(0, 100, 0, 0);
translateAnimation.setDuration(1000);
view.startAnimation(translateAnimation);


}
});


}

Can you help me? Do I have to import something?

Answer

You code is mis-arranged. Do this (setting click listener inside onCreate()):

@Override 
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState); 
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); 
     setContentView(R.layout.activity_main); 

     play.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View view) { 

             TranslateAnimation translateAnimation = new TranslateAnimation(0, 100, 0, 0); 
             translateAnimation.setDuration(1000); 
             view.startAnimation(translateAnimation); 

         } 
    }); 
}
Comments