如何使用OnItemClickListener更改GridView图像项资源?

时间:2013-10-10 12:49:15

标签: android gridview android-gridview ontouchlistener onitemclicklistener

使用OnItemClickListener而不是OnTouchListener点击时,我无法更改GridView图像项资源。我想使用OnItemClickListener的主要原因是我可以点击该项目的position。获得position后,我会用它来确定要更改的图像。当我按下某个项目时,我想将其图像资源更改为image2,并且在未按下时将其更改回image1

使用OnTouchListener很容易,但我无法获取所选GridView项目的position

1 个答案:

答案 0 :(得分:1)

试试这个:

  gridView.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent me) {

                int action = me.getActionMasked();  // MotionEvent types such as ACTION_UP, ACTION_DOWN
                float currentXPosition = me.getX();
                float currentYPosition = me.getY();
                int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition);

                // Access text in the cell, or the object itself
                String s = (String) gridView.getItemAtPosition(position);
                TextView tv = (TextView) gridView.getChildAt(position);
        }
    }