KisnardOnline
KisnardOnline

Reputation: 740

setClickListeners with loop

is it possible to do this with a loop so I dont have to type this 70 times for my rows? This is for Android programming(Java).

 View row1 = findViewById(R.id.row1);
 row1.setOnClickListener(this);
 View row2 = findViewById(R.id.row2);
 row2.setOnClickListener(this);
 View row3 = findViewById(R.id.row3);
 row3.setOnClickListener(this);
 View row4 = findViewById(R.id.row4);
 row4.setOnClickListener(this);
 View row5 = findViewById(R.id.row5);
 row5.setOnClickListener(this);
 View row6 = findViewById(R.id.row6);
 row6.setOnClickListener(this);

Upvotes: 0

Views: 159

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134664

Yeah, as Falmarri said, this is probably not the best way to do what you want, but to answer the question, you could do this:

View[] views = {
    findViewById(R.id.row1),
    findViewById(R.id.row2),
    //etc...
};

for (View v : views) {
    v.setOnClickListener(this);
}

You could do it with a for loop iterating "i" using reflection, but I'd recommend posting what you're ultimately trying to achieve, I'm sure there's a much better way to accomplish this.

Just to hazard a guess, since they're named "rowX", is this just a list of items? If so, use a ListView and an attached onItemClickListener instead.

Upvotes: 1

Related Questions