2012-03-27 92 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個按鈕。然後你只需要爲這些按鈕註冊clickhandlers,並在那裏改變x和y值。

爲了使用您的自定義播放鑑於佈局,你需要添加另一個構造

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

您佈局文件可能看起來像這樣

<?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> 

另外,您可以覆蓋的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 2012-03-28 16:24:16

0

讓您的視圖實現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; 
    }