Search code examples
javaandroidandroid-studiojbutton

Declaring buttons in android studio


What is the best way to declare buttons in Android Studio java class? For example I have buttons & text fields:

TextView t = (TextView) findViewById(R.id.Question);
TextView A = (TextView) findViewById(R.id.AnswerA);
TextView B = (TextView) findViewById(R.id.AnswerB);
TextView C = (TextView) findViewById(R.id.AnswerC);
TextView D = (TextView) findViewById(R.id.AnswerD);
Button next_test = (Button)findViewById(R.id.Next_Text);
Button b = (Button)findViewById(R.id.button);

Android Studio throws errors when I declare them just below the class like so:

public class main extends AppCompatActivity {

TextView t = (TextView) findViewById(R.id.Question);
TextView A = (TextView) findViewById(R.id.AnswerA);
TextView B = (TextView) findViewById(R.id.AnswerB);
TextView C = (TextView) findViewById(R.id.AnswerC);
TextView D = (TextView) findViewById(R.id.AnswerD);
Button next_test = (Button)findViewById(R.id.Next_Text);
Button b = (Button)findViewById(R.id.button);

@Override
protected void onCreate(Bundle savedInstanceState) {..........

It doesn't throw errors when I declare them in the methods they are need in, but then I have to declare them multiple times and also declare final in the oncreate.

Is there any way of declaring them just once?


Solution

  • You must declare your views in onCreate . Put your findViewById methods in onCreate.