0

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!

4

3 回答 3

3

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" ... />
于 2012-05-05T11:15:53.823 回答
0

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);
于 2012-05-05T11:34:56.593 回答
0

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;       
           }        
    }
}
于 2012-05-05T11:48:07.800 回答