Вопрос

Is it possible to get a reference to an XML element such as a button using findViewById globally in the main java class?

I have so many references that I need to keep on calling them all over again multiple times because I can't use the reference I called in the onCreate method.

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");
}

I know that to fix the error would be to reference the button and the textview after the setContentView but the problem is that I need to repeat all my references for each method in the same class.

Это было полезно?

Решение

// 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");
}

Другие советы

You have to create member variables for the Views you want to reference and you initialize them in onCreate() once. Then you reference these variables where you need inside the Activity

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top