Очистка всех изображений вызывает сбой с ClassCastException - PullRequest
0 голосов
/ 01 июня 2018

В игре Tic-Tac-Toe, когда я нажимаю кнопку «Играть снова», она должна очистить все изображения в разделе GRID LAYOUT.

Я реализовал этот код в своем проекте, но с этого момента мое приложениевылетает всякий раз, когда я нажимаю на него.

GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);

    for (int i = 0; i < gridLayout.getChildCount(); i++) {
        ((ImageView) gridLayout.getChildAt(i)).setImageResource(0);
    }

Моя версия плагина Android: 3.1.2

Моя версия Gradle :: 4.4

Мой полный код:

package com.example.darsheel.gameconnect3;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // 0 = yellow, 1 = red;
    int activePlayer = 0;
    boolean gameIsActive = true;

    // 2 means unplayed
    int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2};

    int[][] winningPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};

    public void dropIn(View view) {

        ImageView counter = (ImageView) view;
        int tappedCounter = Integer.parseInt(counter.getTag().toString());

        if (gameState[tappedCounter] == 2 && gameIsActive == true) {

            // This will make translation to -ve Y axis
            counter.setTranslationY(-1000f);

            gameState[tappedCounter] = activePlayer;

            if (activePlayer == 0) {
                counter.setImageResource(R.drawable.yellow);
                activePlayer = 1;
            } else {
                counter.setImageResource(R.drawable.red);
                activePlayer = 0;
            }
            counter.animate().translationYBy(1000f).rotation(3600).setDuration(500);


            for (int[] winningPosition : winningPositions) {

                if ((gameState[winningPosition[0]] == gameState[winningPosition[1]]) && (gameState[winningPosition[1]] == gameState[winningPosition[2]])
                        && (gameState[winningPosition[2]] != 2)) {

                    TextView winnerMsg = (TextView) findViewById(R.id.winnerMessage);

                    // Someone wins
                    gameIsActive = false;

                    String winner = "RED";
                    if (gameState[winningPosition[0]] == 0)
                        winner = "YELLOW";

                    winnerMsg.setText(winner + " has Won!!");
                    LinearLayout layout = (LinearLayout) findViewById(R.id.playAgainLayout);
                    layout.setVisibility(View.VISIBLE);

                }
            }

        }
    }

    public void playAgain(View view) {

        gameIsActive = true;
        LinearLayout layout = (LinearLayout) 
        findViewById(R.id.playAgainLayout);
        layout.setVisibility(View.INVISIBLE);
        activePlayer = 0;

        for (int i = 0; i < gameState.length; i++) {
            gameState[i] = 2;

        }

        GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);

        for (int i = 0; i < gridLayout.getChildCount(); i++) {
            ((ImageView) gridLayout.getChildAt(i)).setImageResource(0);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Мой полный XML-код:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.GridLayout
        android:id="@+id/gridLayout"
        android:layout_width="0dp"
        android:layout_height="360dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/board"
        app:columnCount="3"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.497"
        app:rowCount="3">

        <ImageView
            android:id="@+id/imageView0"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_margin="10dp"
            android:onClick="dropIn"
            android:tag="0"
            app:layout_column="0"
            app:layout_row="0" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:onClick="dropIn"
            android:tag="1"
            app:layout_column="1"
            app:layout_row="0" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="10dp"
            android:onClick="dropIn"
            android:tag="2"
            app:layout_column="2"
            app:layout_row="0" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:onClick="dropIn"
            android:tag="3"
            app:layout_column="0"
            app:layout_row="1" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="20dp"
            android:onClick="dropIn"
            android:tag="4"
            app:layout_column="1"
            app:layout_row="1" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="20dp"
            android:onClick="dropIn"
            android:tag="5"
            app:layout_column="2"
            app:layout_row="1" />

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:onClick="dropIn"
            android:tag="6"
            app:layout_column="0"
            app:layout_row="2" />

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginTop="20dp"
            android:onClick="dropIn"
            android:tag="7"
            app:layout_column="1"
            app:layout_row="2" />


        <ImageView
            android:id="@+id/imageView8"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_marginTop="20dp"
            android:onClick="dropIn"
            android:tag="8"
            app:layout_column="2"
            app:layout_row="2" />

    </android.support.v7.widget.GridLayout>

    <LinearLayout
        android:id="@+id/playAgainLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="#ecf786"
        android:orientation="vertical"
        android:padding="40dp"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/gridLayout"
        app:layout_constraintStart_toStartOf="@+id/gridLayout"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/winnerMessage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="playAgain"
            android:text="Play Again ?" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout> 

LOGCAT info:

        --------- beginning of crash
06-01 19:32:12.218 5059-5059/com.example.darsheel.gameconnect3 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.darsheel.gameconnect3, PID: 5059
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
        at android.view.View.performClick(View.java:6294) 
        at android.view.View$PerformClick.run(View.java:24770) 
        at android.os.Handler.handleCallback(Handler.java:790) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
     Caused by: java.lang.ClassCastException: android.support.v7.widget.GridLayout cannot be cast to android.widget.GridLayout
        at com.example.darsheel.gameconnect3.MainActivity.playAgain(MainActivity.java:80)
        at java.lang.reflect.Method.invoke(Native Method) 
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
        at android.view.View.performClick(View.java:6294) 
        at android.view.View$PerformClick.run(View.java:24770) 
        at android.os.Handler.handleCallback(Handler.java:790) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

enter image description here

1 Ответ

0 голосов
/ 01 июня 2018

Это ясно показывает .ClassCastException с Grid Layout , поэтому просто измените импорт в классе, как показано ниже.

Просто import this.(Справа)

import android.support.v7.widget.GridLayout

Вместо этого.(Неверно)

import android.widget.GridLayout;

Поскольку ваш XML содержит это android.support.v7.widget.GridLayout.

...