Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPatrick Koch
40,498 Pointscall function within creation that function,.....what?
Hi volks,
here is something new for me, Ben was calling the loadPage() function in the loadPage function itself, obviously its working but its a new practise to me. first the code:
private void loadPage(int choice) {
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
// Add the name if placeholder included. Won't add if no placeholder
pageText = String.format(pageText, mName);
mTextView.setText(pageText);
if (mCurrentPage.isFinal()) {
mChoice1.setVisibility(View.INVISIBLE);
mChoice2.setText("PLAY AGAIN");
mChoice2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
else {
mChoice1.setText(mCurrentPage.getChoice1().getText());
mChoice2.setText(mCurrentPage.getChoice2().getText());
mChoice1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoice1().getNextPage();
loadPage(nextPage);
}
});
mChoice2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoice2().getNextPage();
loadPage(nextPage);
}
});
}
}
What I understande, if we run the loadPage function its executing down till the loadPage() function is called again, and its starts to execute from the top. Are those thoughts right or how is that working?
Probably somebody can explain it to me, thanks
greetings Patrick
1 Answer
kunalshitut
5,872 PointsYou are correct. See, what happens is that when you call loadpage(nextPage); inside loadpage(), the loadpage() method is called again with nextPage in place of choice. This is called 'recursion', a programming concept in which a method calls itself again and again . Googling it should give you a better idea.
Patrick Koch
40,498 PointsPatrick Koch
40,498 Pointsthanks a lot Kunal