在片段

时间:2016-04-14 07:17:04

标签: android fragment

当textView更改为GridView时,我的应用程序一直崩溃。

  

04-14 09:18:50.704 6903-6903 / com.example.bernine.practicalsessions E / AndroidRuntime:FATAL EXCEPTION:main java.lang.ClassCastException:android.widget.GridView无法强制转换为android.widget.TextView在com.example.bernine.practicalsessions.TechnologyFragment.onCreateView(Technology Fragment.java:38)

我在XML文件中做错了吗?

<?xml version="1.0" encoding="utf-8"?>
<!--<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" />-->

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />

这是片段类

public class ScienceFragment extends Fragment {

    public static final String ARG_PAGE = "ARG_PAGE";

    private int mPage;

    public static ScienceFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        ScienceFragment fragment = new ScienceFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);
        Toast.makeText(getContext(), "Science", Toast.LENGTH_SHORT).show();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_sports_fragment, container, false);
        TextView textView = (TextView) view;
        textView.setText("Fragment Science #" + mPage);
        return view;
    }
}

当textView被取消注释并且gridview被评论时,该应用程序运行良好。

2 个答案:

答案 0 :(得分:0)

Fragment

中删除此部分代码
TextView textView = (TextView) view;
textView.setText("Fragment Science #" + mPage);

而不是那个把你的GridView逻辑

答案 1 :(得分:0)

从代码中删除TextView并声明您的GridView并为您的GridView制作适配器。

 TextView textView = (TextView) view;
    textView.setText("Fragment Science #" + mPage);

main java.lang.ClassCastException: android.widget.GridView cannot be cast to android.widget.TextView ....

这意味着您仍在使用Textview