我正在尝试创建一个具有 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);
}
}
}