setting onClick listeners for multiple items in an array
I am trying to implement a select list. Each item is an imageview.
When the user clicks a view, a custom dialog opens up showing the 56 ImageViews in a list. The user can then click on one to select it. The imageviews have images named like this items_r1_c1 ... items_r56_c1. I have to implement onClickListeners to each of the imageviews. Instead I did this:private int i; // This is int the outer class.
...
private ImageView [] spec = new ImageView[56];
myView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//set up dialog
try {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.myCustomList);
dialog.setTitle("Select one of 56");
dialog.setCancelable(true);
dialog.show();
String s = null;
//This is where I automate the ImageView object creation
for (i=2; i<=56; i++) {
s = "items_r"+Integer.toString(i)+"_c1";
spec[i] = (ImageView) findViewById(getResources().getIdentifier(s,"drawable",getPackageName()));
spec[i].setOnClickListener(new OnClickListener() {
@Override
开发者_如何学C public void onClick(View v) {
myItem.setItem(Integer.toString(i));
if(i == 0) myItem.setItem("invalid");
Log.e(tag, myItem.getItem());
dialog.dismiss();
}
});
}
} catch (Exception e) {
Log.e(tag, e.toString());
}
}
However I am not getting the behavior I expected.
What am I doing wrong? What is the efficient way of doing this instead of writing 56 onClick listeners. Thank you.For starters I'd put the for( ... )
loop before the call to dialog.show().
To answer your more general question, look at the method ListView.setOnItemClickListener() http://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener).
You'd only have to register one listener on your ListView. When an item in your ListView is clicked you'd end up in the code under void onItemClick(AdapterView<?> parent, View view, int position, long id)
. The position would be the index of the row clicked (corresponding to i in your loop).
精彩评论