简体   繁体   中英

When I try to set a clickListener, app crashes

Every time I run this app on my emulator, the app crashes when I tap the play button:

public class PixelCheckActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pixel_check);
    final Button play = (Button) findViewById(R.id.play);
    // ...40 b's defined here ex: final Button b1 = (Button) findViewById(R.id.b1);
    final Button[][] arr = {
            {b1,b2,b3,b4,b5},
            {b6,b7,b8,b9,b10},
            {b11,b12,b13,b14,b15},
            {b16,b17,b18,b19,b20},
            {b21,b22,b23,b24,b25},
            {b26,b27,b28,b29,b30},
            {b31,b32,b33,b34,b35},
            {b36,b37,b38,b39,b40}
    };
    final View.OnClickListener listener1 = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.pixel_tap_game);
            final View.OnClickListener listener = new View.OnClickListener() {
                @Override
                public void onClick(View view){view.setBackgroundColor(Color.RED);}
            };
            for(int i=0;i<=4;i++){arr[0][i].setOnClickListener(listener);}
        }
    };
    play.setOnClickListener(listener1);
}
}

I think the problem is, the 40 b's are in a different layout file then the play button. So, what do I need to do in order to fix this?

Here is the Logcat crash log: http://i.imgur.com/bCoa7jL.png

If the 40 buttons are in a different layout, if they are not in the layout you inflated in your activity ( R.layout.activity_pixel_check ), then you can't get a reference through findViewById method. The findViewById will return a view reference IF it's in the activity's layout , or null if not . So you will have an array of 40 null references, and when you call arr[0][i].setOnClickListener(listener) you surely get a NullPointerException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM