Look at following android code. IMGS
is a 2 dimensional array of ImageView
. I am adding onClickListener
to it in a for
loop. How to identify which view
has been clicked ? I dont want to iterate over all the 36 elements using view.getId();
.
private static final Integer[] Icons = {
R.drawable.r,
R.drawable.re,
R.drawable.u,
R.drawable.et,
R.drawable.w,
R.drawable.ya
};
private ImageView[][] IMGS= new ImageView[6][6];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMGS[0][0] = (ImageView) findViewById(R.id.immg11);
for (int i=0; i < 6; i++)
{
for (int j=0; j<6; j++)
{
Drawable d = getResources().getDrawable(Icons[i]);
IMGS[i][j].setImageDrawable(d);
IMGS[i][j].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//HOW TO KNOW WHICH VIEW HAS BEEN CLICKED ?
}
});
}
}
}
Notice the View
argument passed to onClick(View v)
? It's the view that was clicked.
You can call v.getId()
to retrieve its id.
Agreed, but there are 36 elements over which i have to iterate if I use this method. Is there a way to know the indexes of clicked IMGS ?
You can use setTag()
to save whatever data you want in each view and retrieve it later with getTag()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.