Reputation: 143
So I have 2 XML layout files.
One is the menu and the other is the app.
So, now I have some buttons on the one XML file and some other buttons on the other file.
So this code works:
setContentView(R.layout.main);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
But if I change the view and write this:
setContentView(R.layout.random);
add_person = (Button) findViewById(R.id.add);
add_person.setOnClickListener(this); //crash here
The app crashes!
Upvotes: 0
Views: 1622
Reputation: 780
You should implement the class as onClickListner
like this:
public class <ClassName> extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
//Hear Yor Logic on Click Event.
break;
}
}
}
Upvotes: 0
Reputation: 132992
try after cleaning current project from Project->Clean.
or you can use
(Button)random.findViewById(R.id.add);
instead of
(Button) findViewById(R.id.add);
Upvotes: 0
Reputation: 40426
add_person
is null so get Nullpointer Exception and you have Button in random.xml which has add as id?
if not then add
<Button android:id="@+id/add" ... />
Upvotes: 3