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 trial
qasimalbaqali
17,839 PointsFun Fact app - how to generate random title AND fact at the same time
So let's say I'm developing an app to display not just a fact but it's title too. For example when the user clicks random fact button I want it to show:
Ants
Ants stretch their legs when they wake up.
how can I do that? Is it possible since it's two different TextViews?
2 Answers
Guilherme Mendonca
3,064 PointsHi Qasmin,
You could do like this:
// Create an array with all questions and answers.
// Answer1 must be the answer of Question1, and so on
String[] questions = { "Question1", "Question2", ...., "Last Question"};
String[] answers = {"Answer1", "Answer2", ..., "Last Answer"};
//Initializing textview variables
final TextView question = (TextView) findViewById(R.id. _text view 1_);
final TextView answer = (TextView) findViewById(R.id. _text view2_);
View.OnClickListener buttonClick = new View.OnClickListener() {
@Override
public void onClick(View view) {
// generating a random number from 0 to array size
Random randomQuest_Answ = new Random();
int number = randomQuest_Answ.nextInt(answer.length);
String currentQuestion = questions[number];
String currentAnswer = answers[number];
// setting question and answer to show on screen
question.setText(currentQuestion);
answer.setText(currentAnswer);
}
}
I think that's it. You will probably have to change the code to fit your program, but this is one solution.
Good Luck!
Kate Hoferkamp
5,205 PointsYes it's possible, just like it was possible to change the color and fact. You can either do it by having two different arrays or a multi-dimensional array. Let me know if you need more help!
qasimalbaqali
17,839 PointsI am a beginner in Java so a step by step would be great if it's not too much to ask!
Kate Hoferkamp
5,205 PointsOkay, no problem. The first question, is are the titles that you are changing going to relate to the facts or are they random? Does a fact always have the same title or can it be different?
qasimalbaqali
17,839 PointsNo, they will have different titles. It will be like a Question and it's answer.