Android - onTouch не работает

это мой код:

public class ViewSecond extends View implements View.OnTouchListener{

private Context context;
private Rect tailleEcran;
private Vibrator vibrator;

private Paint paint;
private Paint monPerso = new Paint();
private Paint flecheHaut = new Paint();
private Paint flecheBas = new Paint();
private Paint flecheGauche = new Paint();
private Paint flecheDroite = new Paint();

private Bitmap bmp, bmpFlecheHaut, bmpFlecheBas, bmpFlecheGauche, bmpFlecheDroite;

private Carte carteActuelle;

public ViewSecond(Context context) {
    super(context);
    this.context = context;
    this.vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
    this.tailleEcran = getWindowSize();

    this.paint = new Paint();
    this.paint.setAntiAlias(true);
    this.paint.setStyle(Paint.Style.FILL);

    // ON S'OCCUPE DU PERSO PRINCIPAL
    monPerso.setColor(Color.RED);
    monPerso.setAntiAlias(false);
    // ON S'OCCUPE DE LA CARTE
    this.carteActuelle = new Carte(1,1,"lol");
    // ON S'OCCUPE DES FLECHES DIRECTIONNEL
    this.flecheHaut   = new Paint();
    this.flecheBas    = new Paint();
    this.flecheGauche = new Paint();
    this.flecheDroite = new Paint();
    bmp             = BitmapFactory.decodeResource(getResources(),R.drawable.flechehaut);
    bmpFlecheHaut   = Bitmap.createScaledBitmap(bmp,(int)(tailleEcran.exactCenterX()*2)/8,(int)(tailleEcran.exactCenterY()*2)/8,false);
    bmp             = BitmapFactory.decodeResource(getResources(),R.drawable.flechebas);
    bmpFlecheBas    = Bitmap.createScaledBitmap(bmp,(int)(tailleEcran.exactCenterX()*2)/8,(int)(tailleEcran.exactCenterY()*2)/8,false);
    bmp             = BitmapFactory.decodeResource(getResources(),R.drawable.flechegauche);
    bmpFlecheGauche = Bitmap.createScaledBitmap(bmp,(int)(tailleEcran.exactCenterX()*2)/8,(int)(tailleEcran.exactCenterY()*2)/8,false);
    bmp             = BitmapFactory.decodeResource(getResources(),R.drawable.flechedroite);
    bmpFlecheDroite = Bitmap.createScaledBitmap(bmp,(int)(tailleEcran.exactCenterX()*2)/8,(int)(tailleEcran.exactCenterY()*2)/8,false);

}

public boolean onTouch(View v, MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    if(((x>100) && (x<550)) && ((y>100) && (y<550))){
        this.vibrator.vibrate(500);
    }
    this.invalidate();
    return false;
}

public void onClick(View v) {
    this.paint.setColor(Color.RED);
    this.invalidate();
}

protected void onDraw(Canvas canvas){
    canvas.drawColor(Color.BLACK);
    canvas.drawCircle(10, 10, 10, monPerso);
    canvas.drawBitmap(bmpFlecheHaut,(int)((tailleEcran.exactCenterX()*2)/8)+10,(int)((tailleEcran.exactCenterY()*2)-(((tailleEcran.exactCenterY()*2)/8)*2)-10),null);
    canvas.drawBitmap(bmpFlecheBas,(int)((tailleEcran.exactCenterX()*2)/8)+10,(int)((tailleEcran.exactCenterY()*2)-(tailleEcran.exactCenterY()*2)/8),null);
    canvas.drawBitmap(bmpFlecheGauche,0,(int)((tailleEcran.exactCenterY()*2)-(tailleEcran.exactCenterY()*2)/5.5),null);
    canvas.drawBitmap(bmpFlecheDroite,(int)((tailleEcran.exactCenterX()*2)/4)+20,(int)((tailleEcran.exactCenterY()*2)-(tailleEcran.exactCenterY()*2)/5.5),null);
}

// CETTE FONCTION RENVOIE UN RECTANGE DE LA TAILLE DE L'ECRAN
Rect getWindowSize() {
    Rect r = new Rect();
    WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    display.getRectSize(r);
    return r;
}}

Я пытаюсь определить, когда пользователь касается экрана, но это не работает, я пытался поместить его (метод onTouch) здесь и в действии, но ничего не происходит: / Есть идеи? Вы видите мои рисунки? Наконец, я хочу обнаружить щелчок по этим изображениям. Спасибо :D


person Antoine Duval    schedule 03.04.2015    source источник
comment
реализовать onTouchListener для обнаружения касания...   -  person Chirag Savsani    schedule 03.04.2015
comment
Как нуб...сорри. Но тоже не работай :/   -  person Antoine Duval    schedule 03.04.2015
comment
если вы расширяете представление, используйте onTouchEvent, а не onTouch   -  person pskink    schedule 03.04.2015


Ответы (2)


Привет, если вы хотите переопределить общедоступное логическое значение onTouch (событие View v, MotionEvent). Если вы хотите обработать весь элемент управления, верните false, в противном случае верните true. В вашем случае вы возвращаете false, обновите его и попробуйте вернуть true. например, см. ниже метод просмотра onTouch.

public boolean onTouch(View view, MotionEvent event) {
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            break; 
        case MotionEvent.ACTION_UP:
            break; 
        case MotionEvent.ACTION_POINTER_DOWN:
            break; 
        case MotionEvent.ACTION_POINTER_UP:
            break; 
        case MotionEvent.ACTION_MOVE:
            break; 
    } 
    _root.invalidate();
    return true; 
}} 

Смотрите, как он возвращает истину. благодарю вас.

person Bhavdip Sagar    schedule 03.04.2015

Вы должны использовать onTouchEvent() вместо простого onTouch() и вернуть в нем true. Если вы вернете true, это означает, что вы использовали событие касания и сообщаете Android, что ему не нужно обрабатывать событие дальше.

public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    if(((x>100) && (x<550)) && ((y>100) && (y<550))){
        this.vibrator.vibrate(500);
    }
    this.invalidate();
    return true;
}
person Paul Freez    schedule 03.04.2015