简体   繁体   English

如何识别单击了哪个“视图”?

[英]How to identify which `view` has been clicked?

Look at following android code. 看下面的android代码。 IMGS is a 2 dimensional array of ImageView . IMGSImageView二维数组。 I am adding onClickListener to it in a for loop. 我在for循环中添加了onClickListener How to identify which view has been clicked ? 如何识别单击了哪个view I dont want to iterate over all the 36 elements using view.getId(); 我不想使用view.getId();遍历所有36个元素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) ? 注意将View参数传递给onClick(View v)吗? It's the view that was clicked. 单击的是该视图。

You can call v.getId() to retrieve its id. 您可以调用v.getId()检索其ID。

Agreed, but there are 36 elements over which i have to iterate if I use this method. 同意,但是如果使用此方法,则必须对36个元素进行迭代。 Is there a way to know the indexes of clicked IMGS ? 有没有办法知道点击的IMGS的索引?

You can use setTag() to save whatever data you want in each view and retrieve it later with getTag() . 您可以使用setTag()在每个视图中保存所需的任何数据,并稍后使用getTag()检索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM