Search code examples
javaandroidreferencefindviewbyid

Global Reference findViewById


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.


Solution

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