So looking back at what’s been accomplished so far; we’ve created the objects in our XML file, we’ve created objects in our StartActivity class that link to them, next up is having the buttons respond when we click on them.
Underneath the code you’ve created that instantiated our objects we’re going to add a call to a new method called create_click_listeners, i.e:
: img_p_cards.add((ImageView) findViewById(R.id.p_card4_img)); img_p_cards.add((ImageView) findViewById(R.id.p_card5_img)); create_click_listeners(); } }
Inside this new method we’re going to create the code required to listen to each of those buttons on your UI. So underneath the onCreate method add the following method:
private void create_click_listeners(){ // CLICKLISTENER FOR THE HIT BUTTON // ================================ but_hit.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { hit_clicked(); } }); // CLICKLISTENER FOR THE STAY BUTTON // ================================= but_stay.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { stay_clicked(); } }); // CLICKLISTENER FOR THE AGAIN BUTTON // ================================== but_again.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { start_again_clicked(); } }); }
These probably look a bit confusing because inside the “setOnClickListener” method we’re creating a new object that has it’s own onClick method? It is all a bit confusing but not worth us getting bogged down in. If you’re making a clickListener, this is just what’s required. The code you want to execute when someone clicks on your button is put inside the onClick method and you can see in our case I’ve created three new methods that allow us to separate the confusing onClick stuff from the actual code we’re trying to execute. So now make sure you create methods that match the ones referred to above. In the end you should end up with something that looks a bit like this:
Notice that I’ve collapsed the “create_click_listeners” method since it’s confusing and detracts from what we’re actually doing here. It doesn’t need any further alteration so collapse it and forget about it!
Righty-O! Now we’re prepared to finally get this app responding to the user!