Reputation: 18130
I have a for loop, but I need it to stop doing anything until I get a response from the user (aka the user selects left or right). I'm doing this in Android, but I'm not sure of the best way to go about this. The "left" and "right" are images. So I'm listening for left or right to be hit before I keep moving on. I need the loop to go on about 50 times. This is what I have so far.
int testlength = 50;
for (int i = 0; i < testlength; i++) {
left.setImageResource(R.drawable.left);
right.setImageResource(R.drawable.right);
//Stop the for loop and get the input from the user
}
Upvotes: 2
Views: 853
Reputation: 1155
You don't need a loop.
Just exit the routine once you have 50 responses:
int count = 0;
String[] responses = new String[50];
left.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
left.setImageResource(R.drawable.left);
right.setImageResource(R.drawable.right);
responses[count] = "Left";
count++;
if(count == 50)
{
// Exit the activity
}
}
};
right.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
left.setImageResource(R.drawable.left);
right.setImageResource(R.drawable.right);
responses[count] = "Right";
count++;
if(count == 50)
{
// Exit the activity
}
}
};
Upvotes: 1
Reputation: 5072
The ideal solution in my opinion would be to use semaphores:
class Example {
private Semaphore sem;
public Example() {
sem = new Semaphore(0);
}
public void onClick(...) {
// Do stuff
sem.release();
}
public void myLoop() {
int testlength = 50;
for (int i = 0; i < testlength; i++) {
left.setImageResource(R.drawable.left);
right.setImageResource(R.drawable.right);
sem.acquire();
}
}
}
Remember that this assumes that myLoop isn't running on the UI thread.
Upvotes: 2
Reputation: 11625
You want to do something like this -
ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
}
});
That is, you want to use an event rather than loop waiting for someone to click. Tight loops are generally a nasty idea.
I got the code from this thread - how to apply click event listener to image in android
Upvotes: 0