Reputation: 3238
I'm new to Android development, so this is probably easy question.
There is Button defined in layout, but when Activity starting I see in debugger this Button is null. How this can happend?
<Button
android:id="@+id/show_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/show_answer_button"/>
Activity:
private Button mShowAnswer;
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
}
});
Upvotes: 0
Views: 102
Reputation: 717
try this:
private Button mShowAnswer;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
}
});
}
Upvotes: 1
Reputation: 2141
According to this comment setContentView()
method is in wrong place, it's must be place before binding button variable and button xml view.
setContentView(R.layout.your_xml_layout_name);
private Button mShowAnswer;
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
Upvotes: 0