是否可以在主java类中全局使用findViewById来引用XML元素(如按钮)?
我有很多引用,我需要多次再次调用它们,因为我不能使用我在onCreate方法中调用的引用。
private long mode;
private final Button playBtn = (Button)findViewById(R.id.playBtn);
private final TextView aboutTitle = (TextView)findViewById(R.id.aboutTitle);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn.setTypeface(robotoThin);
aboutTitle.setText("hello world");
}
我知道修复错误的方法是在setContentView之后引用按钮和textview,但问题是我需要为同一个类中的每个方法重复所有引用。
答案 0 :(得分:1)
// try this way (here i'm declare your both view object as globaly for your class so it can be acccess any where in classs and is created onCreate() at first time and further it used directly)
private long mode;
private Button playBtn;
private TextView aboutTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button)findViewById(R.id.playBtn);
aboutTitle = (TextView)findViewById(R.id.aboutTitle);
playBtn.setTypeface(robotoThin);
aboutTitle.setText("hello world");
}
答案 1 :(得分:0)
您必须为要引用的Views
创建成员变量,并在onCreate()
中初始化它们一次。然后在Activity