0
我想創建一個將有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);
}
}
}
有什麼辦法可以實現它嗎?我的目標是API8,最高可達API17 –
您可以在視圖腳本中使用視圖而不是片段。在這種情況下,你將會犧牲片段生命週期的優勢。只是一個選擇。 – Praga
你可以建議視圖腳蹼的任何好資源? –