为什么在对GridView进行子类化时会出现ClassCastException?

时间:2012-04-16 20:25:10

标签: android

很奇怪;出于某种原因,我很难让GridView的子类正确地进行投射。尝试转换CustomGridView时,我得到Caused by: java.lang.ClassCastException: android.widget.GridView cannot be cast to com.dobydigital.dobixchange.CustomGridView。这是我的代码

CustomGridView.java

import android.widget.GridView;
public class CustomGridView extends GridView {

FileBrowserFragment.java

//# Other stuff omitted for brevity
private CustomGridView gridView;
public class FileBrowserFragment extends Fragment {
//# Stuff
}
//# .........
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    //# This cast here throws the exception
    gridView = (CustomGridView) getView().findViewById(R.id.grid_view);

file_browser.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_node"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<com.dobydigital.dobixchange.CustomGridView
    android:id="@+id/grid_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:numColumns="3"
    android:layout_weight="80" >
    <!-- Preview: listitem=@layout/image_tile -->
</com.dobydigital.dobixchange.CustomGridView>



<Button
    android:id="@+id/btn_confirm"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="Select this Directory" />

</LinearLayout>

我无法弄清楚发生了什么。我以前从来没有遇到过布局的问题。

2 个答案:

答案 0 :(得分:0)

gridView = (CustomGridView) findViewById(R.id.grid_view);

摆脱getView()

答案 1 :(得分:0)

从问题的评论:你不小心膨胀&amp;在onCreateView()中返回错误的布局:)