【发布时间】:2016-02-22 12:01:37
【问题描述】:
在 Android Studio java 类中声明按钮的最佳方式是什么?例如,我有按钮和文本字段:
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 会抛出错误:
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) {..........
当我在它们需要的方法中声明它们时它不会抛出错误,但是我必须多次声明它们并在 oncreate 中声明它们。
有没有办法只声明一次?
【问题讨论】:
-
你应该
declare他们作为类变量,assign在你的onCreate,设置contentView后。
标签: java android android-studio jbutton