views:

110

answers:

1

Hi. I'm new to android developing but right now I'm working on an application that displays Random Facts. Since I don't want it to be in a random order, I would like to have them in a list. I would like to order through them one by one and show them using TextView.

Resources res = getResources();
myString = res.getStringArray(R.array.FactsArray); 

That's what I have so far. If I'm right, that just establishes the array so I can be able to use it later. What I had before was rgenerator which chose a random string from the array and displayed it when I clicked a button.

Resources res = getResources();
myString = res.getStringArray(R.array.myArray); 

fact = myString[rgenerator.nextInt(myString.length)];

TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(fact);

But Like I said, I would like to just order through them one by one when a button is clicked.

+2  A: 

Since you're displaying the strings sequentially, you'll need a counter variable to keep track of where you are in the array. It should be initialized to zero. Each time you click the button it should increment until you reach the end of the array (myString.length - 1).

As far as the actual event handling, that's not hard to do. You just need to create a setOnClickListener() for your button.

    int count = 0;
    Button b1 = (Button) findViewById(R.id.buttonName);
    b1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (count < myString.length) {
                tv.setText(myString[count]);
                count++;
            }
        }
    });
Tyler
Thanks! I have one more question though, if your still reading this... What does the tv mean on "tv.setText(myString[count];"?
Keenan Thompson
I was referring to your posted code which initialized `TextView tv = ...` So to answer your question, `tv.setText(myString[count]);` will set the TextView's text to the current String. Also, you could run that whole conditional statement in one line if you wanted, using `tv.setText(myString[count++]);`
Tyler
OK, thanks for the help
Keenan Thompson
No problem! Please select this as the question's answer and upvote if this was what you were looking for.
Tyler