2 votes

ClassCastException sur les LayoutParams de LinearLayout à AbsListView

Mon application doit afficher une liste avec une fenêtre de texte, une case à cocher et une fenêtre d'image pour chaque ligne. Avant d'ajouter le code pour l'image, tout fonctionnait bien. Mais maintenant, j'obtiens toujours cette exception :

android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams

Je suppose que quelque chose ne va pas avec mon getView() Méthode en Adapter la classe. Je suis nouveau dans le développement Android et j'ai du mal à comprendre le problème et à le trouver. J'ai utilisé la fonction de recherche mais je n'ai pas trouvé de solution. Pouvez-vous m'aider ?

Stack Trace :

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example..myapplication, PID: 17373
              java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
                  at android.widget.ListView.setupChild(ListView.java:1927)
                  at android.widget.ListView.makeAndAddView(ListView.java:1894)
                  at android.widget.ListView.fillDown(ListView.java:792)
                  at android.widget.ListView.fillFromTop(ListView.java:853)
                  at android.widget.ListView.layoutChildren(ListView.java:1731)
                  at android.widget.AbsListView.onLayout(AbsListView.java:2279)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                  at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                  at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
                  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
                  at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
                  at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
                  at android.view.View.layout(View.java:15047)
                  at android.view.ViewGroup.layout(ViewGroup.java:4676)
                  at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2189)
                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1896)
                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1103)
                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6018)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:799)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:599)
                  at android.view.Choreographer.doFrame(Choreographer.java:559)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:784)
                  at android.os.Handler.handleCallback(Handler.java:733)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:157)
                  at android.app.ActivityThread.main(ActivityThread.java:5872)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
                  at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

package com.example.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.Preference;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

ListView lv;
CheckBox checkBox;
ArrayList<Object> items = new ArrayList<>();

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

    //lv mit xml listview verknüpfen
    lv = (ListView) findViewById(R.id.list_view_nahrungsmittel);
    //checkBox mit xml checkbox verbinden
    checkBox = (CheckBox) findViewById(R.id.checkbox);

    //Lebensmittel/Aktivitäten erstellen und zur items Liste hinzufügen
    ItemList gemuese = new ItemList("Gemüse","100g","Karotte\nWirsing\nKohl",R.drawable.ic_cruciferous_vegetables );
    ItemList wasser = new ItemList("Wasser","0,5 Liter","Mineralwasser", R.drawable.ic_beverages);
    ItemList supps = new ItemList("Supplements", "Eine Pille", "D3\nK2\nO3", R.drawable.ic_supp);
    ItemList sport = new ItemList("Sport", "1h", "Laufen\nCrosstrainer\nFahrrad\nPumpen", R.drawable.ic_exercise);
    ItemList meditation = new ItemList("Meditation", "1h", R.drawable.meditation);
    items.add("Nahrungsmittel");
    items.add(wasser);
    items.add(gemuese);
    items.add(supps);
    items.add("Aktivitäten");
    items.add(sport);
    items.add(meditation);

    //ItemListAdapter: Items Liste mit lv verknüpfen
    lv.setAdapter(new ItemListAdapter(this, items, R.layout.row_item ));

    //Click on Items
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {    //??
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Object obj = items.get(position);

            if (obj instanceof ItemList) {
                //Intent erstellen
                Intent intent = new Intent(MainActivity.this, DetailActivity.class);

                //Informationen aus dem Item Objekt ziehen
                ItemList item = (ItemList) obj;
                String title = item.getTitle();
                String portion = item.getPortion();
                String typ = item.getTyp();

                //Informationen übergeben
                intent.putExtra("EXTRA_TITLE", title);
                intent.putExtra("EXTRA_PORTION", portion);
                intent.putExtra("EXTRA_TYP", typ);

                //neue Aktivität starten
                startActivity(intent);
            }
        }
    });

}

}

Classe d'adaptateur

package com.example.myapplication;
import android.content.Context;
import android.provider.ContactsContract; 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class ItemListAdapter extends BaseAdapter {

private LayoutInflater inflater;
private ArrayList<Object> itemArray;
int resIdImage;
private static final int TYPE_ListElement = 0;
private static final int TYPE_DIVIDER = 1;

public ItemListAdapter(Context context, ArrayList<Object> itemArray, int resource) {
    this.itemArray = itemArray;
    this.resIdImage = resource;
    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return itemArray.size();
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public Object getItem(int position) {
    return itemArray.get(position);
}

@Override
public int getViewTypeCount() {
    // TYPE_PERSON and TYPE_DIVIDER
    return 2;
}

@Override
public int getItemViewType(int position) {
    if (getItem(position) instanceof ItemList) {
        return TYPE_ListElement;
    }

    return TYPE_DIVIDER;
}

@Override
public boolean isEnabled(int position) {
    return (getItemViewType(position) == TYPE_ListElement);
}

public class DataHolder{
    ImageView imageView;
    TextView textView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    DataHolder holder =  null;
    int type = getItemViewType(position);
    if (convertView == null) {
        switch (type) {
            case TYPE_ListElement:
               View view = inflater.inflate(resIdImage, parent, false);
                convertView = inflater.inflate(R.layout.row_item, (ViewGroup) view, false);
                holder = new DataHolder();
                holder.imageView = (ImageView) convertView.findViewById(R.id.image);
                holder.textView = (TextView) convertView.findViewById(R.id.nameLabel);
                convertView.setTag(holder);
                break;
            case TYPE_DIVIDER:
                convertView = inflater.inflate(R.layout.row_header, parent, false);
                break;
        }
    }
    else {
        holder = (DataHolder)convertView.getTag();
    }

    switch (type) {
        case TYPE_ListElement:
            ItemList item = (ItemList) getItem(position);
            TextView name = (TextView)convertView.findViewById(R.id.nameLabel);
            name.setText(item.getTitle());
            holder.textView.setText(item.getTitle());
            holder.imageView.setImageResource(item.resIdImage);
            break;
        case TYPE_DIVIDER:
            TextView title = (TextView)convertView.findViewById(R.id.headerTitle);
            String titleString = (String)getItem(position);
            title.setText(titleString);
            break;
    }

    return convertView;
}
}

disposition des rangées

<?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"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@mipmap/ic_launcher"
    android:layout_gravity="center"
    android:layout_margin="20dp"/>

<TextView
    android:id="@+id/nameLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:layout_margin="20dp"
    android:text="Name"
    android:layout_weight="1"
/>

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:layout_gravity="right|center"
    android:gravity="right|center"
    />

1voto

Ben P. Points 25894

Ce morceau de votre getView() La méthode semble très suspecte :

case TYPE_ListElement:
      View view = inflater.inflate(resIdImage, parent, false);
      convertView = inflater.inflate(R.layout.row_item, (ViewGroup) view, false);
      ...

C'est vraiment bizarre de voir deux appels à inflate() en getView() . Je soupçonne que vous voulez changer cela comme suit :

case TYPE_ListElement:
      convertView = inflater.inflate(resIdImage, parent, false);
      ...

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X