0

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

这很容易使用OnTouchListener但是我无法获得所选GridView项目的position

+0

见我的答案,并尝试 – Goofy

回答

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); 
     } 
    } 
+0

这是伟大的,但现在我的问题是,我想改变ImageView的资源,但是当我用'ImageView的IV =(ImageView的)GridView控件。 getChildAt(position);'由于触及的'Child'是父'LinearLayout'而不是它的子'ImageView',所以出现了ClassCastException。在这种情况下,我如何获得孩子的ImageView? –

相关问题