我在 FragmentActivity 中使用 ViewPager。现在,每当我的 Activity 启动时,我都会将position
值传递给newinstance
我的片段的方法。从那里我的片段现在将选择可绘制的资源 id 并将其设置为背景。
我的片段活动
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.ViewGroup;
import android.view.Window;
public class HowToActivity extends FragmentActivity {
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_out_bottom, R.anim.slide_in_top);
}
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // remove title
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.viewPager_howto);
setContentView(mViewPager);
getWindow().setLayout(LayoutParams.MATCH_PARENT /* width */ , LayoutParams.MATCH_PARENT /* height */);
FragmentManager fm = this.getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fm){
@Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
super.setPrimaryItem(container, position, object);
}
@Override
public int getCount() {
return 3;
}
@Override
public Fragment getItem(int position) {
return HowToFragment.newInstance(position);
}
});
}
}
我的片段
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 static int image_pos;
private int[] image_id = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3};
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;
}
}
它总是显示image_2.png
而不是image_1
启动时。然后您需要一直滑动到image_3
或2
位置以将其固定image_1
在该0
位置上。来回滑动只会显示在每个片段中0
。1
image_2
任何想法我做错了什么?