简体   繁体   中英

Error: android.widget.LinearLayout cannot be cast to android.widget.ImageView

There was already someone else with a similar problem, but I couldn't understand the anwser and I wasn't able to add a coment to receive more informations. So please help me!

This is my main JavaClass

package ch.androidnewcomer.muckenfangfinal;


import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Date;
import java.util.Random;

public class GameActivity extends Activity implements View.OnClickListener,         Runnable{

public static final int DELAY_MILLIS = 1000;
public static final int ZEITSCHEIBEN = 60;
public float massstab;
private int runde;
private int punkte;
private int muecken;
private int gefangeneMuecken;
private int zeit;
private static final long HOECHSTALTER_MS = 2000;
private Random zufallsgenerator = new Random();
private ViewGroup spielbereich;
private Handler handler = new Handler();
private boolean spielLaeuft;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);
    massstab = getResources().getDisplayMetrics().density;
    spielbereich = (ViewGroup)findViewById(R.id.spielbereich);
    spielStarten();

}




private void spielStarten() {
    spielLaeuft = true;
    runde = 0;
    punkte = 0;
    starteRunde();
}



private void bildschirmAktualisieren() {
    TextView tvPunkte = (TextView)findViewById(R.id.points);
    tvPunkte.setText(Integer.toString(punkte));

    TextView tvRunde = (TextView)findViewById(R.id.round);
    tvRunde.setText(Integer.toString(runde));

    TextView tvTreffer = (TextView)findViewById(R.id.hits);
    tvTreffer.setText(Integer.toString(gefangeneMuecken));

    TextView tvZeit = (TextView)findViewById(R.id.time);
    tvZeit.setText(Integer.toString(zeit/(1000/DELAY_MILLIS)));

    FrameLayout flTreffer = (FrameLayout)findViewById(R.id.bar_hits);
    FrameLayout flZeit = (FrameLayout)findViewById(R.id.bar_time);


    ViewGroup.LayoutParams lpTreffer = flTreffer.getLayoutParams();
    lpTreffer.width = Math.round( massstab * 300 * Math.min(                        gefangeneMuecken,muecken) / muecken);

    ViewGroup.LayoutParams lpZeit = flZeit.getLayoutParams();
    lpZeit.width = Math.round( massstab * zeit *300 / ZEITSCHEIBEN);


}





private void zeitHerunterzaehlen() {
    zeit = zeit - 1;
    if(zeit % (1000/DELAY_MILLIS) == 0) {
        float zufallszahl = zufallsgenerator.nextFloat();
        double wahrscheinlichkeit = muecken * 1.5;
        if (wahrscheinlichkeit > 1) {
            eineMueckeAnzeigen();
            if (zufallszahl < wahrscheinlichkeit - 1) {
                eineMueckeAnzeigen();
            }
        } else {
            if (zufallszahl < wahrscheinlichkeit) {
                eineMueckeAnzeigen();
            }
        }
    }

    mueckenVerschwinden();
    bildschirmAktualisieren();
    if(!pruefeSpielende()) {
        if(!pruefeRundenende()) {
            handler.postDelayed(this, DELAY_MILLIS);
        }
    }
}



private boolean pruefeRundenende()  {
    if (gefangeneMuecken >= muecken) {
        starteRunde();
        return true;
    }
    return false;
}


private void starteRunde() {
    runde = runde +1;
    muecken = runde *10;
    gefangeneMuecken = 0;
    zeit = ZEITSCHEIBEN;
    bildschirmAktualisieren();
    handler.postDelayed(this, DELAY_MILLIS);

}

private boolean pruefeSpielende() {
    if(zeit == 0 && gefangeneMuecken < muecken) {
        gameOver();
        return  true;
    }
    return false;
}













private void gameOver() {
    Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
    dialog.setContentView(R.layout.gameover);
    dialog.show();
    spielLaeuft = false;
}

private void mueckenVerschwinden() {
    int nummer=0;
    while (nummer < spielbereich.getChildCount()) {
        ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
        Date geburtsdatum = (Date) muecke.getTag(R.id.geburtsdatum);
        long alter = (new Date()).getTime() - geburtsdatum.getTime();
        if(alter > HOECHSTALTER_MS) {
            spielbereich.removeView(muecke);
        }else {
            nummer++;
        }
    }
}




private void eineMueckeAnzeigen() {
    int breite = spielbereich.getWidth();
    int hoehe = spielbereich.getHeight();
    int muecke_breite = (int) Math.round(massstab* 60);
    int muecke_hoehe = (int) Math.round(massstab*49);
    int links = zufallsgenerator.nextInt(breite - muecke_breite);
    int oben = zufallsgenerator.nextInt(hoehe - muecke_hoehe);

    ImageView muecke = new ImageView(this);
    muecke.setImageResource(R.drawable.muecke);
    muecke.setOnClickListener(this);
    muecke.setTag(R.id.geburtsdatum, new Date());

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(muecke_breite, muecke_hoehe);
    params.leftMargin = links;
    params.topMargin = oben;
    params.gravity = Gravity.TOP + Gravity.LEFT;

    spielbereich.addView(muecke,params);

}





@Override
public void onClick(View muecke) {
    gefangeneMuecken++;
    punkte += 100;
    bildschirmAktualisieren();
    spielbereich.removeView(muecke);
}

@Override
public void run() {
    zeitHerunterzaehlen();
}

}

The FrameLayout, where I'm trying to display the 'muecke - mosquito' is called 'spielbereich' meaning as much as playground.

And this is the LogCat

12-28 16:19:26.449 5302-5302/ch.androidnewcomer.muckenfangfinal       E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                  Process: ch.androidnewcomer.muckenfangfinal, PID: 5302
                                                                                  java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ImageView
                                                                                      at        ch.androidnewcomer.muckenfangfinal.GameActivity.mueckenVerschwinden(GameActivity.java:168)
                                                                                  at ch.androidnewcomer.muckenfangfinal.GameActivity.zeitHerunterzaehlen(GameActivity.java:104)
                                                                                  at ch.androidnewcomer.muckenfangfinal.GameActivity.run(GameActivity.java:218)
                                                                                  at android.os.Handler.handleCallback(Handler.java:751)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:154)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

And here is my xmlLayout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="ch.androidnewcomer.muckenfangfinal.GameActivity">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="61dp">

        <TextView
            android:id="@+id/round"
            android:layout_width="136dp"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:textSize="21sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/points"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:text="TextView"
            android:textSize="21sp"
            android:textStyle="bold" />


    </FrameLayout>

    <FrameLayout
        android:id="@+id/spielbereich"
        android:layout_width="match_parent"
        android:layout_height="332dp"
        android:layout_weight="1">

        <LinearLayout
            android:id="@+id/hintergrundlinearlayout"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:layout_gravity="bottom"
            android:orientation="vertical">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="35dp">

                <FrameLayout
                    android:id="@+id/bar_hits"
                    android:layout_width="50dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:background="@android:color/holo_orange_dark">

                </FrameLayout>

                <TextView
                    android:id="@+id/hits"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:text="@string/hits"
                    android:textSize="15sp"
                    android:textStyle="bold" />
            </FrameLayout>


            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">


                <FrameLayout
                    android:id="@+id/bar_time"
                    android:layout_width="50dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="center_vertical"
                    android:background="@android:color/holo_orange_light">

                </FrameLayout>

                <TextView
                    android:id="@+id/time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:text="@string/time" />
            </FrameLayout>
        </LinearLayout>

    </FrameLayout>

</LinearLayout>

if you need anymore informations, please tell me. It would be great if you could tell me exactely how I have to change the code, because I'm really a beginner.

you are casting a linear layout to imageview.You are trying to get a child of frame layout which is a linear layout but you casted it to a image view.thats why this error was happened. casting it to the linearlayout will solve this error.

This is your layout with id spielbereich

<FrameLayout
        android:id="@+id/spielbereich"
        android:layout_width="match_parent"
        android:layout_height="332dp"
        android:layout_weight="1">

        <LinearLayout
            android:id="@+id/hintergrundlinearlayout"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:layout_gravity="bottom"
            android:orientation="vertical">

And this is the code where you are trying to cast the childView into an ImageView

private void mueckenVerschwinden() {
    int nummer=0;
    while (nummer < spielbereich.getChildCount()) {
        ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
        Date geburtsdatum = (Date) muecke.getTag(R.id.geburtsdatum);
        long alter = (new Date()).getTime() - geburtsdatum.getTime();
        if(alter > HOECHSTALTER_MS) {
            spielbereich.removeView(muecke);
        }else {
            nummer++;
        }
    }
}

ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);

This line is giving you a cast error because nummer = 0 at this point and spielbereich.getChildAt(0) is a LinearLayout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM