2012-03-27 14 views
0

私は、オブジェクトを左、右、および上に移動するアプリケーションを作成しています。ここに私のコードは次のとおりです。ビットマップで押された場所

package com.bjo.er; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.view.View; 


public class Play extends View { 
    int x=0; 
    int y=0; 
    Bitmap object; 

    public Play(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     object = BitmapFactory.decodeResource(getResources(), R.drawable.brid); 
    } 
    @Override 
    public void onDraw(Canvas canvas){ 
     super.onDraw(canvas); 
     canvas.drawColor(Color.GRAY); 
     canvas.drawBitmap(object, x, y, null); 
     invalidate(); 
    } 
} 

私は、ユーザーがオブジェクトを移動するには、画面上で利用できるプレス三つの異なる場所になりたいです。いくつかの助けは非常に便利です。

答えて

0

これにはRelativeLayoutを使用できます。再生ビューを画面に表示させ、再生ビューの上に3つのボタンを配置します。次に、それらのボタンのクリックハンドラーを登録し、そこのxとyの値を変更するだけです。

あなたはあなたのレイアウトファイルは、この

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <com.bjo.er.Play 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

    <Button 
     android:id="@+id/button_left" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:text="left" 
     android:layout_alignParentLeft="true" 
     android:layout_centerVertical="true" /> 
    <Button 
     android:id="@+id/button_right" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:text="right" 
     android:layout_alignParentRight="true" 
     android:layout_centerVertical="true" /> 
</RelativeLayout> 

ようになり

public Play(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

また、あなたのプレイにonTouchEventオーバーライドすることができ、別のコンストラクタを追加する必要があるレイアウトでカスタムプレイビューを使用するためには、ビュー。

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    final int action = event.getAction(); 
    if (action == MotionEvent.ACTION_DOWN) { 
       //make use of event.getX() and event.getY() 
      } 
    return super.onTouchEvent(event); 
} 
+0

I'amはすでにので、私がする別のクラスに遊びクラスを実行していますむしろxmlファイルを別のファイルにインポートしますか? – user1241123

0

EX、あなたのビューがonTouchListenerを実装してください:textView.setOnTouchListener(this); 仕事の残りの部分は、例えば、onTouchになります。

float previousx,previousy; 
int counter; 

    public boolean onTouch(View v, MotionEvent event) { 

    switch (event.getAction()) { 


    case MotionEvent.ACTION_UP: 
    float x =event.getX(); 
float y =event.getY(); 
if(x==previousx && y==previousy) 
Toast.makeText(this, "Touch a diffrent position",Toast.LENGTH_SHORT).show(); 
else{ 
counter+=1; 
if(counter==3) { 
//move your object.Put code here 
counter=0; 
} 
}  
previousx=x; 
previousy=y; 
break; 
    } 
    return true; 
    } 
関連する問題