为什么我的片段中的ViewPager不起作用?

时间:2013-10-08 03:22:47

标签: android android-fragments android-viewpager

我正在尝试创建一个具有ViewPager的片段。当调用并提交所述片段时,它仅显示第一个图像并且它不可被移动。有什么想法如何实现这个?

这是片段

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class HowToFragment extends Fragment {

    private ViewPager mViewPager;
    private MyAdapter mAdapter;
    private int[] image_id = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3};

    private static int image_pos = 0;

    public static Fragment newInstance(int pos){
        image_pos = pos;
        return new HowToFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_how_to_image, container, false);
        v.setBackgroundResource(image_id[image_pos]);
        return v;
    }

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

        mViewPager = new ViewPager(getActivity());
        mViewPager.setId(R.id.viewPager_howto);
        FragmentManager fm = getFragmentManager();
        mAdapter = new MyAdapter(fm);
        new setAdapterTask().execute();

    }

    private class setAdapterTask extends AsyncTask<Void,Void,Void>{
          protected Void doInBackground(Void... params) {
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                       mViewPager.setAdapter(mAdapter);
            }
    }

    private class MyAdapter extends FragmentStatePagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
            // TODO Auto-generated constructor stub
        }

        @Override
        public int getCount() {
            return image_id.length;

        }
        @Override
        public Fragment getItem(int position) {
             return HowToFragment.newInstance(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            FragmentManager manager = getFragmentManager();
            FragmentTransaction ft = manager.beginTransaction();
            ft.remove((Fragment) object);
            ft.commit();

            super.destroyItem(container, position, object);
        }


    }
}

1 个答案:

答案 0 :(得分:0)

我怀疑你是否试图在Android版本中运行此应用程序,而不是Honeycomb。你想要实现的是嵌套片段。嵌套片段支持仅在软糖4.2之后可用。