如何将ViewPager放入片段中?

时间:2013-02-14 15:26:38

标签: android view android-fragments

我有一个有3个片段的应用程序。它在xml中定义如下。 :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id = "@+id/activity_main_large"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" xmlns:tools="http://schemas.android.com/tools">

     <fragment
         android:id="@+id/menu_category_fragment"
         android:name="com.thesis.menubook.MenuCategory"
         android:layout_width="0dip"
         android:layout_height="match_parent"
         android:layout_weight="0.14"
         layout="@layout/activity_menu_category" />

     <fragment
         android:id="@+id/menu_fragment"
         android:name="com.thesis.menubook.MenuFragment"
         android:layout_width="0dip"
         android:layout_height="match_parent"
         android:layout_weight="0.71"
         layout="@layout/activity_menu_fragment" />


     <fragment
         android:id="@+id/orderlist_fragment"
         android:name="com.thesis.menubook.OrderListFragment"
         android:layout_width="167dp"
         android:layout_height="match_parent"
         layout="@layout/activity_order_list" />

</LinearLayout>

我希望中间片段是“可跳过”的,用户将翻页。因此com.thesis.menubook.MenuFragment会调用包含View Pager

的布局

这是java文件:

package com.thesis.menubook;

import android.annotation.TargetApi;
import android.support.v4.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MenuFragment extends FragmentActivity {
    private MyAdapter mAdapter;
    private ViewPager mPager;

    static String [] menu_name = {"a", "b","c"};
    static String [] menu_description = {"0", "1", "2"};



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_fragment);
        mAdapter = new MyAdapter(getSupportFragmentManager());

        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
    }

    public static class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                return new ImageFragment(R.drawable.caesar_salad,menu_name[0], menu_description[0]);
            case 1:
                return new ImageFragment(R.drawable.albondigas_pasta,menu_name[1], menu_description[1]);
            case 2:
                return new ImageFragment(R.drawable.salmon_entrada,menu_name[2], menu_description[2]);
            default:
                return null;
            }
        }
    }
}

这是定义了viewpager的MenuFragment的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent" android:gravity="bottom|top" xmlns:android="http://schemas.android.com/apk/res/android" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp">

    <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</RelativeLayout>

这是ImageFragment类:

package com.thesis.menubook;



import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ImageFragment extends Fragment {


      private  int imageResourceId;
      private String name;
      private String namedescription;



    public ImageFragment(int imageResource, String name2, String description) {
        this.imageResourceId = imageResource;    
        this.name = name2;
        this.namedescription = description;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("Test", "hello");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_menu, container, false);


        RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.main_layout);
        layout.setBackgroundResource(imageResourceId);
        TextView tv = (TextView) view.findViewById(R.id.menu_name);
        tv.setText(name.toString());
        TextView tv2 = (TextView) view.findViewById(R.id.menu_description);
        tv2.setText(namedescription.toString());

        Button button = (Button) view.findViewById(R.id.add);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


            TextView tx = (TextView) v.findViewById(R.id.menu_name);
            String mname = tx.toString();   

            TextView tx1 = (TextView) v.findViewById(R.id.menu_description);
            String mdesc = tx1.toString();

            EditText et = (EditText) v.findViewById(R.id.editText1);
            String q = et.toString();




            }
        });

        return view;

}


} 

这是寻呼机内容的ImageFragment的xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:gravity="top|bottom|center_vertical" 
    android:background="@drawable/caesar_salad" 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingLeft="16dp" 
    android:paddingRight="16dp" 
    android:paddingTop="16dp"
    android:id="@+id/main_layout"
    >

    <TextView 
        android:id="@+id/menu_name" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="@string/menu_name" 
        android:textSize="40sp"
        android:background="#2f000000" android:textColor = "@android:color/white"/>

    <TextView 
        android:id="@+id/menu_description" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_below="@id/menu_name"    
        android:background="#2f000000"  
        android:textColor="@android:color/white" 
        android:textSize="20sp" 
        android:textStyle="italic" 
        android:typeface="sans"
        android:text ="@string/menu_description"
        android:layout_margin="10dp">

    </TextView>

    <Button 
        android:id="@+id/add" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignBaseline="@+id/editText1" 
        android:layout_toRightOf="@+id/editText1" 
        android:layout_centerHorizontal="true" 
        android:text="@string/add" 
        android:textColor="@android:color/white"/>
    <EditText 
        android:id="@+id/editText1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignBottom="@+id/quantity" android:layout_alignTop="@+id/quantity" android:layout_centerHorizontal="true" android:layout_toRightOf="@+id/quantity" android:layout_marginLeft="5dp" android:background="@android:color/white" android:ems="2" android:inputType="number">
        <requestFocus />
    </EditText>

    <TextView 
        android:id="@+id/quantity" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignLeft="@+id/menu_description" 
        android:layout_alignParentBottom="true" 
        android:layout_marginBottom="20dp" 
        android:background="#2f000000" 
        android:text="@string/quantity" 
        android:textColor="@android:color/white" 
        android:textSize="25sp" 
        android:textStyle="italic" 
        android:typeface="sans"/>
    <Button 
        android:id="@+id/viewOrdersList" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignBaseline="@+id/editText1" 
        android:layout_toRightOf="@+id/add" 
        android:layout_centerHorizontal="true" 
        android:text="@string/orderlist" 
        android:textColor="@android:color/white"/>



</RelativeLayout>

所以从我的角度来看,我觉得它会很好,因为我认为它具有良好的层次结构?

但我收到这样的错误:

02-14 23:22:13.499: E/AndroidRuntime(399): Caused by: java.lang.ClassCastException: com.thesis.menubook.MenuFragment cannot be cast to android.app.Fragment

您不能将Viewpager转换为片段吗?

这是我的LogCat:

02-14 23:22:13.499: E/AndroidRuntime(399): FATAL EXCEPTION: main
02-14 23:22:13.499: E/AndroidRuntime(399): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thesis.menubook/com.thesis.menubook.MenuMain}: android.view.InflateException: Binary XML file line #16: Error inflating class fragment
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1748)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.ActivityThread.access$1500(ActivityThread.java:122)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.os.Looper.loop(Looper.java:132)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.ActivityThread.main(ActivityThread.java:4025)
02-14 23:22:13.499: E/AndroidRuntime(399):  at java.lang.reflect.Method.invokeNative(Native Method)
02-14 23:22:13.499: E/AndroidRuntime(399):  at java.lang.reflect.Method.invoke(Method.java:491)
02-14 23:22:13.499: E/AndroidRuntime(399):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
02-14 23:22:13.499: E/AndroidRuntime(399):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
02-14 23:22:13.499: E/AndroidRuntime(399):  at dalvik.system.NativeStart.main(Native Method)
02-14 23:22:13.499: E/AndroidRuntime(399): Caused by: android.view.InflateException: Binary XML file line #16: Error inflating class fragment
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
02-14 23:22:13.499: E/AndroidRuntime(399):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:223)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.Activity.setContentView(Activity.java:1780)
02-14 23:22:13.499: E/AndroidRuntime(399):  at com.thesis.menubook.MenuMain.onCreate(MenuMain.java:13)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
02-14 23:22:13.499: E/AndroidRuntime(399):  ... 11 more
02-14 23:22:13.499: E/AndroidRuntime(399): Caused by: java.lang.ClassCastException: com.thesis.menubook.MenuFragment cannot be cast to android.app.Fragment
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.Fragment.instantiate(Fragment.java:493)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.Fragment.instantiate(Fragment.java:468)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.app.Activity.onCreateView(Activity.java:4132)
02-14 23:22:13.499: E/AndroidRuntime(399):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664)
02-14 23:22:13.499: E/AndroidRuntime(399):  ... 20 more
02-14 23:22:13.979: D/dalvikvm(399): GC_CONCURRENT freed 328K, 6% free 7419K/7879K, paused 9ms+41ms
02-14 23:22:22.750: I/Process(399): Sending signal. PID: 399 SIG: 9

2 个答案:

答案 0 :(得分:3)

您的ViewPager属于ImageFragment而不是MenuFragmentFragmentActivity

的一部分

您必须在ViewPager中设置ImageFragment(在您的onCreateView中使用您的inflater)

ViewPager移至ImageFragment

private ViewPager mPager;

用你的inflater设置它:

mPager = (ViewPager) view.findViewById(R.id.pager);

评论后编辑:不要更改XML

  • 你有一个FragmentActivity,布局是你发布的第一个XML(3个片段所在的位置)===&gt; 所以ViewPager不在这里
  • 每个Fragment类通过onCreateView自行处理它自己的布局,并返回要显示的片段===&gt; 这是ViewPager
  • 的地方

答案 1 :(得分:1)

 <fragment
         android:id="@+id/menu_fragment"
         android:name="com.thesis.menubook.MenuFragment"
         android:layout_width="0dip"
         android:layout_height="match_parent"
         android:layout_weight="0.71"
         layout="@layout/activity_menu_fragment" />

com.thesis.menubook.MenuFragment扩展了FragmentActivity。这是一个活动,而不是片段。这就是你得到ClassCastException的原因。