Micky
Micky

Reputation: 512

Java Android - Casting Parent to Child to Child

Update: I was being stupid thinking its different in this case. You can't cast a Parent to a Child full stop ;)


I'm going mad.

I have a class:

public class ActivityMonitorItemView Extends LinearLayout

Now I'm using a LayoutInflator to return a LinearLayout. But as this returns a View I'm first casting to a LinearLayout like so:

LinearLayout sillyLayout = (LinearLayout) vi.inflate(R.layout.activity_monitor_item, null);

But now when I try cast sillyLayout to ActivityMonitorItemView..

ActivityMonitorItemView amtv = (ActivityMonitorItemView) sillyLayout;

I get a ClassCastException...

Any Ideas? (Actual code used below)

@Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ActivityMonitorItemView v = (ActivityMonitorItemView) convertView;
        if(v == null)
        {
            LayoutInflater vi = (LayoutInflater)OurViewManager.getAnswersRef().getCurrentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            LinearLayout t = (LinearLayout) vi.inflate(R.layout.activity_monitor_item, null);

            v = (ActivityMonitorItemView) t;
            v.LinkUpToTask(listItems.get(position));
        }


        return v;
    }

Upvotes: 1

Views: 562

Answers (1)

Nathan Schwermann
Nathan Schwermann

Reputation: 31503

unless the view are inflating is actually an ActivityMonitorItemView then you will get the exception. You must in your xml file, give the full name of your class. So instead of LinearLayout it would be like

<com.example.ActivityMonitorItemView
  android:layout_width="wrap_content"
  android:layout_height="wrap_conetent"
  android:id="@+id/tester"/>

hope this helps

Upvotes: 1

Related Questions