Tintinabulator Zea
Tintinabulator Zea

Reputation: 2807

How to select GridView item and use onTouchListener in getView?(they seem to cancel each other out)

When i use an onTouchListener in the getView of my adapter the line

android:listSelector="@drawable/circle"

immediately stops working, if I set onTouch to return false it works again, however then the ACTION_DOWN ACTION_UP dosent work properly.

Heres what i have in onTouch

image.setOnTouchListener(new View.OnTouchListener() {
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                Assets.playMusic(songID, false);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {              
                Assets.mediaPlayer.stop();
                Assets.mediaPlayer = null;
                }

            return true;
        }

    }); 

Its suppose to play music for as long as you have a finger held on the item and when you release it should stop the music. And it works well when returning true. However for some reason the circle stops appearing behind the tapped items. If it is set to false the circle appears, but then action_up dosent stop the music

ive tried using .setSelected .setActivated .setEnabled and none of them work please help

Also i want it to work kinda like snapchats camera button, tap it and it does one thing, hold it and it does something for duration of your hold. I was going to use time variables in the Action up and down. but if anyone knows another way to do this id appreciate info about that too

Upvotes: 0

Views: 653

Answers (1)

Joaquin Iurchuk
Joaquin Iurchuk

Reputation: 5627

In this situation is not encouraged to attach an OnTouchListener to the image, but to the items of the GridView instead.

You should have something like this:

GridView gridview = (GridView) findViewById(R.id.the_gridview_id);
gridview.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, final View v, int position, long id) {
        doSomething();
    }
});

EDIT: In order to know how much time a view is pressed, you can do something like this:

// this goes somewhere in your class:
long lastDown;
long lastDuration;

...


// this goes wherever you setup your button listener:
gridview.setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(View v, MotionEvent event) {
      if(event.getAction() == MotionEvent.ACTION_DOWN) {
         lastDown = System.currentTimeMillis();
      } else if (event.getAction() == MotionEvent.ACTION_UP) {
         lastDuration = System.currentTimeMillis() - lastDown;
      }
   }
};

Upvotes: 1

Related Questions