You can't initialize View
s outside of a method like this
CheckBox cb1 = (CheckBox) findViewById(R.id.cb1);
CheckBox cb2 = (CheckBox) findViewById(R.id.cb2);
because that would mean that these lines run before onCreate()
which results in these variables being null
and throw a NPE
when you try to call methods on these variables. This is because you call setContentView(R.layout.your_layout)
inside of onCreate()
and your Views
"live" inside of that layout
. This means that they can't be initialized until your layout
has been inflated
by calling setContentView()
. You must call setContentView()
before trying to initialize your Views
. There is no way around that part.
What some people do that might help is to create a separate function that initializes these variables just after setContentView()
is called. Something like this
public class MyActivity
// declare your Views so they are global to the class
TextView tv;
// more views
@Override
public void onCreat(stuff)
{
// super call
setContentView(R.layout.my_layout);
init();
then in your init()
function initialize all of the Views
you have declared
private void init()
{
tv = (TextView) findViewById(R.id.myTextView);
// more initializations
}
but you can just initialize them in onCreate()
, onResume()
or wherever as long as it's after setContentView()
Declaring and initializing them in this way will make sure they are all available to other functions, listeners, inner classes, etc... of the Activity
. And if you have a lot of Views
it may lessen the "clutter" a bit.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…