简体   繁体   中英

ClassCastException when trying to cast FrameLayout to subclass

In Android, I have a ListFragment. On the ListFragment I want to store a Custom View Object on which I plan to do some further work. Since it looks like the type of View Object returned from OnCreateView is a FrameLayout, I have defined my Custom View Object to derive from FrameLayout.

So, basically my Custom View Class looks like:

public class MyCustomView extends FrameLayout {
    public MyCustomView(Context context) { super(context); }
    public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); }
    public MyCustomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
    public MyCustomView(Context context, AttributeSet attrs, int defStyle, int defStyleRes) { super(context, attrs, defStyle, defStyleRes); }
}

My OnCreateView method in my ListFragment implementation looks like:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getActivity(), android.R.layout.simple_list_item_1,
            new String[]{ "one", "two", "three"});
    setListAdapter(adapter);

    MyCustomView myView = (MyCustomView)super.onCreateView(inflater, container, savedInstanceState);
    return myView;
}

But with this code I get an exception: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to ...myApp.MyCustomView

How can I solve this?

You aren't using your MyCustomView anywhere.

When you call super.onCreateView(inflater, container, savedInstanceState); , you are letting the base class ( ListFragment ) handle creating the layout for your fragment, and the framework's ListFragment class has no idea that you created a MyCustomView or how to use it.

Instead, you need to create a layout XML file that uses MyCustomView , and inflate that layout instead. You will end up with something like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getActivity(), android.R.layout.simple_list_item_1,
            new String[]{ "one", "two", "three"});
    setListAdapter(adapter);

    View layout = inflater.inflate(R.layout.list_fragment_layout, container, false);
    MyCustomView myView = (MyCustomView) layout.findViewById(R.id.custom_view_id);

    return layout;
}

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