2016-10-15 1 views
0

Avant de commencer, j'ai essayé d'examiner les autres questions qui sont similaires à ceci, mais je ne peux pas dire pourquoi le xml me dit que gameview n'existe pas. Je sais que je fais quelque chose de mal Je ne peux pas comprendre quoi.Comment implémenter XML textView et les boutons dans GameView?


J'ai eu quelques boutons et textViews dans mon XML et je veux être en mesure de les utiliser dans mon activité où le contentView est défini comme Gameview. Est-ce faisable?

Dans mon xml j'ai quatre boutons et ils ont tous une propriété onClick où ils envoient (couleur), soit RVB ou jaune. En fonction de ce que l'utilisateur clique, je veux définir la réponse comme un int différent. Si leur réponse est correcte, je veux qu'une nouvelle couleur apparaisse via la méthode generateNewWord. Cependant, dans mon xml je reçois l'erreur

« n'a pas pu être trouvé dans les catégories suivantes: - com.example.ali.colormatch2.surfaceview.Gameview, même si j'ai une classe Gameview

Mon xml. fichier, activity_color_match.xml:

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 

xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/activity_color_match" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.ali.colormatch2.ColorMatch2"> 

<com.exmple.ali.colormatch2.surfaceview.GameView 
    android:id="@+id/gameView" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

<TextView 
    android:text="@string/mainColor" 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center_horizontal" 
    android:textColor="@android:color/background_dark" 
    android:textSize="100dp" 
    android:layout_marginBottom="104dp" 
    android:textAppearance="@style/TextAppearance.AppCompat.Display3" 
    android:layout_above="@+id/button3" 
    android:layout_centerHorizontal="true" /> 

<Button 
    android:layout_width="150dp" 
    android:layout_height="60dp" 
    android:id="@+id/button" 
    android:background="#000080" 
    android:onClick="sendBlue" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" /> 

<Button 
    android:layout_height="60dp" 
    android:id="@+id/button2" 
    android:background="#ffff00" 
    android:elevation="0dp" 
    android:layout_width="150dp" 
    android:onClick="sendYellow" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" /> 

<Button 
    android:layout_width="150dp" 
    android:layout_height="60dp" 
    android:id="@+id/button3" 
    android:background="@android:color/holo_red_dark" 
    android:onClick="sendRed" 
    android:layout_above="@+id/button" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginBottom="19dp" /> 

<Button 
    android:layout_width="150dp" 
    android:layout_height="60dp" 
    android:id="@+id/button4" 
    android:background="@android:color/holo_green_dark" 
    android:onClick="sendGreen" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" 
    android:layout_alignBottom="@+id/button3" /> 

<TextView 
    android:text="Score:" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    android:id="@+id/textView4" /> 

<TextView 

    android:text="@string/matchText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView3" 
    android:textAppearance="@style/TextAppearance.AppCompat.Body2" 
    android:textSize="25dp" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" /> 


</RelativeLayout> 

Mon ColorMatch2.java:

package com.example.ali.colormatch2; 

import android.app.Activity; 
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import android.widget.RelativeLayout; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.widget.ImageView; 
import android.widget.TextView; 

import java.util.Random; 

public class ColorMatch2 extends Activity { 

// gameView will be the view of the game 
// It will also hold the logic of the game 
// and respond to screen touches as well 
GameView gameView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // Initialize gameView and set it as the view 
    gameView = new GameView(this); 
    setContentView(gameView); 
    TextView textView3, textView2, textView4; 
    textView3 = (TextView) findViewById(R.id.textView3); 
    textView2 = (TextView) findViewById(R.id.textView2); 
    textView4 = (TextView) findViewById(R.id.textView4); 

} 

// GameView class will go here 

// Here is our implementation of GameView 
// It is an inner class. 
// Note how the final closing curly brace } 

// Notice we implement runnable so we have 
// A thread and can override the run method. 
class GameView extends SurfaceView implements Runnable { 

    // This is our thread 
    Thread gameThread = null; 

    // This is new. We need a SurfaceHolder 
    // When we use Paint and Canvas in a thread 
    // We will see it in action in the draw method soon. 
    SurfaceHolder ourHolder; 

    // A boolean which we will set and unset 
    // when the game is running- or not. 
    volatile boolean playing; 

    // A Canvas and a Paint object 
    Canvas canvas; 
    Paint paint; 

    // This variable tracks the game frame rate 
    long fps; 

    // This is used to help calculate the fps 
    private long timeThisFrame; 

    //My variables 
    int answer; 
    int correctAnswer; 
    int score = 0; 
    int randomInt2, randomInt1; 
    int count = 0; 
    boolean matchColor = true, matchText = false, firstTime = true; 



    // When the we initialize (call new()) on gameView 
    public GameView(Context context) { 
     // The next line of code asks the 
     // SurfaceView class to set up our object. 
     // How kind., 
     super(context); 

     // Initialize ourHolder and paint objects 
     ourHolder = getHolder(); 
     paint = new Paint(); 

     // Set our boolean to true - game on! 
     playing = true; 

    } 

    @Override 
    public void run() { 
     while (playing) { 

      // Capture the current time in milliseconds in startFrameTime 
      long startFrameTime = System.currentTimeMillis(); 

      // Update the frame 
      update(); 

      // Draw the frame 
      draw(); 

      // Calculate the fps this frame 
      // We can then use the result to 
      // time animations and more. 
      timeThisFrame = System.currentTimeMillis() - startFrameTime; 
      if (timeThisFrame > 0) { 
       fps = 1000/timeThisFrame; 
      } 

     } 

    } 


public void update() { 
     if (firstTime) { 
      generateNewWord(); 
      firstTime = false; 
     } 

     if (answer == correctAnswer) { 
      score++; 
      count++; 
      generateNewWord(); 
     } 
     //else { 
     // quit(); 
     // } 


     if (count % 5 == 0) { 
      if (matchColor) { 
       textView3.setText(getString(R.string.gameSetting2)); // might need to add context with this - check http://stackoverflow.com/questions/10698945/reference-string-resource-from-code 
       matchText = true; 
       matchColor = false; 
      } else if (matchText) { 
       textView3.setText(getString(R.string.gameSetting1)); 
       matchColor = true; 
       matchText = false; 
      } 
     } 
    } 


    public void generateNewWord() { 
     //randomly select between red, green, blue, yellow 
     Random rand = new Random(); 
     randomInt1 = rand.nextInt(4) + 1; // assigns randomInt a value between 1 - 4 
     randomInt2 = rand.nextInt(4) + 1; 

     if (randomInt1 ==1){ 
      textView2.setText(R.string.Red); 
     } 
     else if (randomInt1 ==2){ 
      textView2.setText(R.string.Green); 
     } 
     else if (randomInt1 == 3){ 
      textView2.setText(R.string.Blue); 
     } 
     else if (randomInt1 == 4){ 
      textView2.setText(R.string.Yellow); 
     } 


     //randomly select hex codes between rgby 
     if (randomInt2 ==1){ 
      textView2.setTextColor(0xffcc0000); 
     } 
     else if (randomInt2 ==2){ 
      textView2.setTextColor(0xff669900); 
     } 
     else if (randomInt2 == 3){ 
      textView2.setTextColor(0xff000080); 
     } 
     else if (randomInt2 == 4){ 
      textView2.setTextColor(0xffffff00); 
     } 

     if (matchColor) { 
      correctAnswer = randomInt2; 
     } 
     else if(matchText){ 
      correctAnswer = randomInt1; 
     } 
    } 

    // Draw the newly updated scene 
    public void draw() { 

     // Make sure our drawing surface is valid or we crash 
     if (ourHolder.getSurface().isValid()) { 
      // Lock the canvas ready to draw 
      canvas = ourHolder.lockCanvas(); 

      // Draw the background color 
      canvas.drawColor(Color.argb(255, 255, 255, 255)); 

      // Make the text a bit bigger 
      paint.setTextSize(30); 

      // Display the current score on the screen 
      canvas.drawText("Score:" + score, 20, 40, paint); 


      // Draw everything to the screen 
      ourHolder.unlockCanvasAndPost(canvas); 
     } 

    } 

    // If SimpleGameEngine Activity is paused/stopped 
    // shutdown our thread. 
    public void pause() { 
     playing = false; 
     try { 
      gameThread.join(); 
     } catch (InterruptedException e) { 
      Log.e("Error:", "joining thread"); 
     } 

    } 

    // If SimpleGameEngine Activity is started then 
    // start our thread. 
    public void resume() { 
     playing = true; 
     gameThread = new Thread(this); 
     gameThread.start(); 
    } 


    /*public void sendBlue(View view){ 
     answer = 2; 
    } 
    public void sendRed(View view){ 
     answer = 1; 
    } 
    public void sendYellow(View view){ 
     answer = 4; 
    } 
    public void sendGreen(View view){ 
     answer = 3; 
    }*/ 

    //@Override 
    public int getAnswer(MotionEvent motionEvent) { 

     public void sendBlue(View view){ 
      answer = 2; 
     } 
     public void sendRed(View view){ 
      answer = 1; 
     } 
     public void sendYellow(View view){ 
      answer = 4; 
     } 
     public void sendGreen(View view){ 
      answer = 3; 
     } 
     return answer; 
    } 

} 

// This is the end of our GameView inner class 

// More SimpleGameEngine methods will go here 

// This method executes when the player starts the game 
@Override 
protected void onResume() { 
    super.onResume(); 

    // Tell the gameView resume method to execute 
    gameView.resume(); 
} 

// This method executes when the player quits the game 
@Override 
protected void onPause() { 
    super.onPause(); 

    // Tell the gameView pause method to execute 
    gameView.pause(); 
} 

} 

Je voudrais aussi noter que je pourrais probablement vous déplacer en utilisant setTextV IEW en faisant ma méthode draw() ce qui suit, mais cela ne résout pas le problème de pouvoir utiliser les boutons du fichier xml:

public void draw() { 

     // Make sure our drawing surface is valid or we crash 
     if (ourHolder.getSurface().isValid()) { 
      // Lock the canvas ready to draw 
      canvas = ourHolder.lockCanvas(); 

      // Draw the background color 
      canvas.drawColor(Color.argb(255, 255, 255, 255)); 

      // Make the text a bit bigger 
      paint.setTextSize(30); 

      // Display the current score on the screen 
      canvas.drawText("Score:" + score, 20, 40, paint); 

      if (randomInt2 ==1){ 
       paint.setColor(Color.argb(255, 255, 0, 0));    } 
      else if (randomInt2 ==2){ 
       paint.setColor(Color.argb(255, 0, 191, 255));    } 
      else if (randomInt2 == 3){ 
       paint.setColor(Color.argb(255, 0, 128, 0));    } 
      else if (randomInt2 == 4){ 
       paint.setColor(Color.argb(255, 255, 255, 0));    } 


      paint.setTextSize(60); 

      if (randomInt1 ==1){ 
       canvas.drawText("Red" , 100, 100, paint); 
      } 
      else if (randomInt1 ==2){ 
       canvas.drawText("Green" , 100, 100, paint); 
      } 
      else if (randomInt1 == 3){ 
       canvas.drawText("Blue" , 100, 100, paint); 
      } 
      else if (randomInt1 == 4){ 
       canvas.drawText("Yellow" , 100, 100, paint); 
      } 

      // Draw everything to the screen 
      ourHolder.unlockCanvasAndPost(canvas); 
     } 

    } 

Et voici mon fichier de chaînes:

<resources> 
<string name="app_name">ColorMatch</string> 
<string name="gameSetting1">Match the COLOR</string> 
<string name="gameSetting2">Match the TEXT</string> 
<string name="Red">Red</string> 
<string name="Green">Green </string> 
<string name="Blue">Blue</string> 
<string name="Yellow">Yellow</string> 
<string name="matchText">Test</string> 
<string name="mainColor">Test</string> 
<string name="score">Score:</string> 

</resources> 

Edit: Merci à Nongthonbam Tonthoi j'ai compris comment corriger l'erreur XML. Cependant, dans ma classe GameView publique maintenant séparée pour le code des boutons, il est dit que les méthodes ne sont jamais utilisées. Que dois-je ajouter pour corriger cela et m'assurer qu'un utilisateur qui clique sur un bouton modifie correctement la valeur de la réponse int?

Code pour les boutons. En plus de les enlever d'être à l'intérieur de la méthode RenvoieQuestion, le reste de ma classe Gameview est le même:

 public void sendBlue(View view){ 
     answer = 2; 
    } 
    public void sendRed(View view){ 
    answer = 1; 
    } 
    public void sendYellow(View view){ 
    answer = 4; 
    } 
    public void sendGreen(View view){ 
    answer = 3; 
    } 

Répondre

0

Essayez de changer cette ligne:

<com.exmple.ali.colormatch2.surfaceview.GameView 

à:

<com.exmple.ali.colormatch2.GameView 
+0

J'ai essayé, mais il me donne toujours la même erreur de la classe suivante ne peut pas être trouvé: Johnny

+0

Ne pas faire de GameView une classe interne, en faire une classe publique distincte, puis faites com.exmple. ali.Gam eView –

+0

Merci, cela semblait être la bonne chose à faire. XML ne donne désormais aucune erreur de rendu. Cependant, j'ai toujours quelques problèmes avec l'utilisation de la classe GameView. – Johnny