2011-11-28 73 views
1

即时通讯开发一个应用程序,它具有对特定图像的选择图像作为一个指数该活动将开始,但我不知道如何设置onClickListener或onTouchListener在画布继承人我的代码onClickListener在画布

public class DrawView extends View implements OnTouchListener { 

LinearLayout mLayout; 
Bitmap index; 
Bitmap book; 
Bitmap bird; 
Bitmap game; 
Bitmap mail; 
Bitmap music; 
Bitmap torch; 
Paint paint; 

public DrawView(Context context) { 
    super(context); 

    setFocusable(true); 
    setFocusableInTouchMode(true); 
    this.setOnTouchListener(this); 

    index = BitmapFactory.decodeResource(getResources(), R.drawable.photo1); 
    book = BitmapFactory.decodeResource(getResources(), R.drawable.book); 
    game = BitmapFactory.decodeResource(getResources(), R.drawable.game); 
    music = BitmapFactory.decodeResource(getResources(), R.drawable.music); 
} 

public void onDraw(Canvas canvas){ 
    paint = new Paint(); 
    Bitmap indexcanvas = Bitmap.createScaledBitmap(index, canvas.getWidth(), 
                canvas.getHeight(), true); 
    canvas.drawBitmap(indexcanvas, 0, 0, paint); 
    canvas.drawBitmap(book, 160, 100, paint); 
    canvas.drawBitmap(game, 30, 10, paint); 
    canvas.drawBitmap(music, 80, 50, paint); 
} 

public boolean onTouch(View v, MotionEvent event) { 
    return false; 
} 

如有任何人知道如何为特定图像添加onClickListener,例如这里如果我点击Book,bookActivity就会开始。

回答

4

尝试这样的事:

public boolean onTouch(View v, MotionEvent event) { 
    if((event.getX(0)>=160) && 
     (event.getY(0)>=100) && 
    (event.getX(0)<=160+BOOK_IMG_WIDTH) && 
     (event.getY(0)<=100+BOOK_IMG_HEIGHT)) 
     { 
      //book selected 
     } 
    return true; 
} 
+0

即时通讯尝试通过你的方式,但我得到错误“运算符&&是未定义的参数类型(S)布尔,浮动”......请任何其他选项 –

+0

试图围绕操作数与括号。我编辑了我的代码 – Style

+0

它的工作正常,没有错误,现在感谢你 –

0

使用ImageView,而不是位图,并把它添加到您的布局:

book = new ImageView(context); 
book.setImageResource(R.drawable.book); 
book.setOnTouchListener(new View.OnTouchListener() { 
     public boolean onTouch(View v, MotionEvent event) { 
      /*...*/ 
     } 
    };); 
+0

我想在XY坐标中设置图像....所以我不能在XY中设置图像在ImageResource协调... –

0

保存图像COORDS在一个ArrayList。在上下文上设置OnClickListener,获取已点击的点坐标,在数组列表中找到图像并执行某些操作:)

+0

编写,但如何更新画布,因为它内部的onDraw()方法的视图 – Pranav