在Fragment onCreateView方法中可以做些什么?

时间:2013-07-22 14:20:50

标签: android android-fragments

我所拥有的是3个布局。 fragment_tagfragment_stundefragment_fach

fach应位于stunde stundetag {/ 1}}。

在fach中有一些TextView我想设置文本。

所以到目前为止我的代码是:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LinearLayout tag = (LinearLayout)inflater.inflate(R.layout.fragment_tag, container, true);

        database = new Database(context);

        database.open();

        for (int j = 1; j < 12; j++) {
            LinearLayout stunde = (LinearLayout) inflater.inflate(R.layout.fragment_stunde, tag, true);
            String[][] vplanDaten = database.getVplan(Integer.valueOf(DateHelper.get(DateHelper.WEEK_OF_YEAR)), index + 1, j);

            for (int k = 0; k < vplanDaten.length; k++) {
                LinearLayout fach = (LinearLayout) inflater.inflate(R.layout.fragment_fach, stunde, true);

                TextView fach_lehrer = (TextView) fach.findViewById(R.id.textView_lehrer);
                TextView fach_fach = (TextView) fach.findViewById(R.id.textView_fach);
                TextView fach_raum = (TextView) fach.findViewById(R.id.textView_raum);

                fach_lehrer.setText(vplanDaten[k][0]);
                fach_fach.setText(vplanDaten[k][1]);
                fach_raum.setText(vplanDaten[k][2]);
            }
        }
        database.close();
        return tag;
    }

但这给了我一个错误:

 java.lang.ClassCastException: android.support.v4.view.ViewPager cannot be cast to android.widget.LinearLayout
        at de.MayerhoferSimon.Vertretungsplan.TagFragment.onCreateView(TagFragment.java:56)

那么如何更改我想要做的代码?

2 个答案:

答案 0 :(得分:1)

尝试进行以下更改:

LinearLayout tag = (LinearLayout)inflater.inflate(R.layout.fragment_tag, container, true);

为:

LinearLayout tag = (LinearLayout)(inflater.inflate(R.layout.fragment_tag, null)).findViewById(R.id.idOfTag);

类似地:

LinearLayout stunde = (LinearLayout) inflater.inflate(R.layout.fragment_stunde, tag, true);

为:

LinearLayout stunde = (LinearLayout)(inflater.inflate(R.layout.fragment_stunde, null)).findViewById(R.id.idOfStunde);

LinearLayout fach = (LinearLayout) inflater.inflate(R.layout.fragment_fach, stunde, true);

为:

LinearLayout fach = (LinearLayout)(inflater.inflate(R.layout.fragment_fach, null)).findViewById(R.id.idOfFach);

答案 1 :(得分:0)

LinearLayout更改为类似的视图:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View tag = inflater.inflate(R.layout.fragment_tag, container, true);
       //Everything else...
    return tag;
}

另外我相信你只能按onCreateView给一个视图充气,否则布局会相互替换。您需要有三个单独的片段,每个片段都会为自己的视图充气,并从顶级父活动中单独调用这些片段。