2012-11-05 3 views
3

편집 : LogCat을 살펴 봤는데 com.example.playground를 부 풀릴 수 없다고했습니다. 나는 com.game.myapp.Playground가 필요하다는 것을 깨달았다. 그것을 바꾼 후에 효과가있었습니다.Android에서 게임 중력 생성 (계속)?

최근 안드로이드 앱 (link)에서 중력이 작동하지 않는 이유는 최근 물었습니다. 아직 문제가 있습니다. 보기를 클래스 "놀이터"로 변경했지만 지금은 강제로 닫습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

package com.game.myapp; 

import android.app.Activity; 
import android.graphics.Canvas; 
import android.graphics.Paint; 
import android.os.Bundle; 


public class InGame extends Activity{ 

Playground v; 

private int radius; 
    private int xPosition; 
    private int yPosition; 
    private Paint paint; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Rewrite this, it sucks. Seriously. 
     super.onCreate(savedInstanceState); 
     v = new Playground(this); 
     setContentView(v); 
    } 

    public InGame(int x, int y, int radius, int color) 
    { 
     this.xPosition = x; this.yPosition = y; this.radius = radius; 
     paint = new Paint(color); 
    } 

    void moveBall(int x, int y){ 
     xPosition = x; yPosition =y;   
    } 

    void onDraw(Canvas canvas){ 
      canvas.drawCircle(xPosition, yPosition, radius, paint); 
    }  
} 

놀이터 클래스 :

package com.game.myapp; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.view.View; 

public class Playground extends View{ 

public static InGame ball; 

public Playground(Context context) { 
    super(context); 
    // TODO Auto-generated constructor stub 
} 


    @Override 
    public void onDraw(Canvas canvas) 
    { 
     super.onDraw(canvas); 
     if (ball != null){ 
      ball.onDraw(canvas); 
     } 
    } 

} 

을 heres 로그 캣 :

11-04 16:36:33.945: D/dalvikvm(13177): newInstance failed: no <init>() 

11-04 16:36:33.949: D/AndroidRuntime(13177): Shutting down VM 

11-04 16:36:33.949: W/dalvikvm(13177): threadid=1: thread exiting with uncaught exception (group=0x4001e578) 

11-04 16:36:33.953: E/AndroidRuntime(13177): FATAL EXCEPTION: main 

11-04 16:36:33.953: E/AndroidRuntime(13177): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.game.myapp/com.game.myapp.InGame}: java.lang.InstantiationException: com.game.myapp.InGame 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.os.Handler.dispatchMessage(Handler.java:99) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.os.Looper.loop(Looper.java:130) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.ActivityThread.main(ActivityThread.java:3687) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at java.lang.reflect.Method.invokeNative(Native Method) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at java.lang.reflect.Method.invoke(Method.java:507) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at dalvik.system.NativeStart.main(Native Method) 

11-04 16:36:33.953: E/AndroidRuntime(13177): Caused by: java.lang.InstantiationException: com.game.myapp.InGame 

11-04 16:36:33.953: E/AndroidRuntime(13177): at java.lang.Class.newInstanceImpl(Native Method) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at java.lang.Class.newInstance(Class.java:1409) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.Instrumentation.newActivity(Instrumentation.java:1021) 

11-04 16:36:33.953: E/AndroidRuntime(13177): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565) 

11-04 16:36:33.953: E/AndroidRuntime(13177): ... 11 more 
+2

안녕하세요 요르단. 왜 Ball 클래스에 모든 코드를 넣으려고 했습니까? 당신은 공으로 활동을 사용해서는 안됩니다! 너도 알다시피, 내가 너에게 이것을 쓰고 그것을 게시하는 것이 더 빠를 것이다! 제발, 제발 내 충고를 받아 들여. 클래스와 객체 지향 프로그래밍에 대해 알아보고 Android 태클을 시도하십시오. 당신은 OOP의 기초를 이해하지 못한다면, 성공하지 못할 것이며, 과정에서 많은 시간을 잃을 것입니다. – Simon

답변

4

다음은 전체 코드입니다. 방금이 편지를 썼다. 그것은 작동합니다. 나는 액티비티에 타이머를 추가하여 공을 매초 10 픽셀 씩 오른쪽 아래로 이동했습니다. 그것을 배우고, 그것을 배우고, 당신의 필요에 적응 시키십시오.

볼 클래스.

package com.example; 

import android.graphics.Canvas; 
import android.graphics.Paint; 

public class Ball{ 

    private int radius; 
    private int xPosition; 
    private int yPosition; 
    private int color; 
    private Paint paint; 

    public Ball(int x, int y, int radius, int color) 
    { 
     this.xPosition = x; this.yPosition = y; this.radius = radius; 
     paint = new Paint(); 
     paint.setColor(color); 
    } 

    int getX(){return this.xPosition;} 
    int getY(){return this.yPosition;} 

    void moveBall(int x, int y){ 
     xPosition = x; yPosition =y; 
    } 

    void onDraw(Canvas canvas){ 
     canvas.drawCircle(xPosition, yPosition, radius, paint); 
    } 

} 

놀이터 클래스

package com.example; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.util.AttributeSet; 
import android.widget.ImageView; 

public class Playground extends ImageView { 

    private Ball ball; 

    public Playground(Context context) { 
     this(context,null); 
    } 

    public Playground(Context context, AttributeSet attrs) { 
     this(context, attrs,0); 
    } 

    public Playground(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    public void setBall(Ball ball){ 
     this.ball = ball; 
    } 

    @Override 
    public void onDraw(Canvas canvas) 
    { 
     super.onDraw(canvas); 
     if (ball != null){ 
      ball.onDraw(canvas); 
     } 
    } 

} 

활동 클래스

package com.example; 

import android.app.Activity; 
import android.graphics.Color; 
import android.os.Bundle; 

import java.util.Timer; 
import java.util.TimerTask; 

public class MyActivity extends Activity { 
    /** 
    * Called when the activity is first created. 
    */ 

    Playground playground; 
    Ball ball; 
    Timer myTimer; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     playground = (Playground) findViewById(R.id.playground); 

     ball = new Ball(100, 100, 20, Color.RED); 

     playground.setBall(ball); 

     myTimer = new Timer(); 
     myTimer.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       Update(); 
      } 

     }, 0, 1000); 
    } 

    private void Update() { 
     this.runOnUiThread(moveBall); 
    } 

    private Runnable moveBall = new Runnable() { 
     public void run() { 
      ball.moveBall(ball.getX() + 10, ball.getY() + 10); 
      playground.invalidate(); 
     } 
    }; 


} 

[편집] XML OOP에 대한

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:orientation="vertical" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent"> 
    <com.example.Playground 
      android:id="@+id/playground" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"/> 
</LinearLayout> 

요점.

공에는 놀이터 나 활동에 대한 지식이 없습니다. 그것은 캔버스에 그릴 것을 요구하는 뭔가에 의해 호출되는 메서드가 있지만 모든 알고, 그것은 보이지 않는 캔버스, 또는 단추의 캔버스 또는 비트 맵 캔버스 수 있습니다 - 그것은 않습니다. 알고 있거나 알 필요가있다. 그 문제를 걱정할 방법을 찾는 것은 무엇이든합니다.

놀이터에는 활동이나 볼에 대한 지식이 없습니다. 그것은 에 Ball 클래스의 인스턴스가있을 수 있으며,있는 경우에는 onDraw 메서드라고 불러야하지만 볼이 무엇인지 그리는 지 알지 못합니다. 공은 그것에 대해 걱정합니다.

액티비티에는 볼이나 놀이터에 대한 지식이 없으며, 각각 하나가 있고 볼 이동 방법을 호출 한 다음 놀이터에 다시 그리기를 지시합니다.

요점은, 그리기 방법, 이동 방법 및 기타 모든 부분을 레코딩없이 변경할 수 있다는 것입니다 (일반적으로 OK).예를 들어, Ball 클래스의 onDraw를 변경하여 사각형을 그릴 수 있습니다. 물론, 클래스의 이름은 이제 나쁜 선택이지만 당신은 그 아이디어를 얻습니다. ...

+0

와우! 지금은 훨씬 더 의미가 있습니다! 나는 정확한 코드를 사용했으나 강제로 닫습니다. Activity 클래스로서 MainActivity, activity_main.xml에서 메인 클래스 인 MainActivity와 xml을 넣었습니다. 무슨 일이 일어나고 있는지 잘 모르겠습니다. 그래서 LogCat을 지금 당장 사용하고 있습니다. 고마워요, 그것은 훨씬 깨끗하고 쉽게 보입니다! – Jordan

+0

또한, 일단이 문제를 해결하면 OOP를 먼저 시도하고 해결할 것입니다. 먼저 배웠다면 안드로이드가 훨씬 쉬워 진 것처럼 느낍니다. – Jordan

+0

놀이터 클래스에서 오류가 발생했습니다 : 공공 setBall (볼 공)에서 "메서드의 반환 형식이 없습니다"라는 메시지가 표시되므로 공개 공백으로 변경해야합니다. 그러나 내가 그것을 바꿀 때, 그것은 강제로 닫는다. LogCat이 게시물에 있습니다. – Jordan

2

당신은 안드로이드 인스턴스화 할 수 있도록 필요하다, 당신의 InGameActivity에 디폴트 생성자가 없습니다.

명시 적 생성자가 있으면 암시 적 no-arg 생성자가 정의되지 않습니다. 멤버를 기본값으로 초기화하는 자신의 인수가없는 생성자를 제공해야 할 수도 있습니다.

명시 적 생성자를 삭제하고 초기화를 onCreate(Bundle) 메서드에 넣습니다.

+0

그것은 이미 있었지만, 감사합니다 – Jordan

+0

내 편집을 확인하십시오. –

+0

감사합니다. arg가없는 생성자를 어떻게 광고합니까? – Jordan