开发者

Navigating an Array (Android String Array)

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.

开发者_如何学JAVAResources 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.


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++;
            }
        }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜