在 viewpager 中显示预选项目

Showing pre-selected item in viewpager

我有一个网格视图。单击 gridview 中的任何项目,我将转到包含 gridview 的所有项目的 viewpager/FragmentStatePagerAdapter。我希望视图寻呼机显示所选项目。 Viewpager 总是加载第一项。如何解决这个问题?

Activity:

我在购买中收到来自 gridview 的选定选项Activity 意图 intent = getIntent(); pos = intent.getIntExtra("selected",0);

public class 购买Activity 扩展 AppCompatActivity {

SharedPreferences preferences,sharedPreferences;
final String[] categoryName = new String[]{"Science","Arts","Engineering","Medical"};
ArrayList<Integer> choices = new ArrayList<>();
ArrayList<BuyHorizontalPageModel> buyList = new ArrayList<>();
ViewPager viewPager;
int selected;
BuySwipeAdapter swipeAdapter;
int pos;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_buy);
    preferences = this.getSharedPreferences("com.example.sabmad.basenav", Context.MODE_PRIVATE);
    //preferences = this.getSharedPreferences("com.example.sabmad.basenav", Context.MODE_PRIVATE);
    int choiceSingle = preferences.getInt("single",0);
    int choiceFilter = preferences.getInt("filter",0);

    //Log.i("single",Integer.toString(choiceSingle));
    //Log.i("filter",Integer.toString(choiceFilter));
    //Log.i("previous",Integer.toString(previous));

    Intent intent = getIntent();
    pos = intent.getIntExtra("selected",0);
    Log.i("item from grid",Integer.toString(pos));
    viewPager = (ViewPager)findViewById(R.id.buyPageView);
    viewPager.setCurrentItem(pos);
    //getSupportFragmentManager().get
    swipeAdapter = new BuySwipeAdapter(getSupportFragmentManager(),buyList);
    viewPager.setAdapter(swipeAdapter);

    viewPager.setOffscreenPageLimit(1);



    if(choiceSingle>0){

        ParseQuery<ParseObject> query =new ParseQuery<ParseObject>("SellBook");
        query.whereEqualTo("book_category",categoryName[choiceSingle-1]);
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                if(e==null){
                    for(ParseObject object : objects){
                        ParseFile file = object.getParseFile("book_image");
                        String user_id = object.getString("user_id");
                        String price = object.getString("book_price");
                        String condition = object.getString("book_condition");
                        BuyHorizontalPageModel buyModel = new BuyHorizontalPageModel(file,price,condition,user_id);
                        buyList.add(buyModel);
                        swipeAdapter.notifyDataSetChanged();

                    }
                }
            }
        });

    }if(choiceSingle == 0 && choiceFilter >0){
        choices.clear();
        ArrayList<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
        UserFilterChoice filterChoice = new UserFilterChoice();
        choices = filterChoice.choices(choiceFilter);
        for(int i = 0; i < choices.size(); i++){
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("SellBook");
            query.whereEqualTo("book_category",categoryName[choices.get(i)-1]);
            queries.add(query);
        }
        ParseQuery<ParseObject> query = ParseQuery.or(queries);
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                if(e==null){
                    for( ParseObject object:objects){
                        ParseFile file = object.getParseFile("book_image");
                        String user_id = object.getString("user_id");
                        String price = object.getString("book_price");
                        String condition = object.getString("book_condition");
                        BuyHorizontalPageModel buyModel = new BuyHorizontalPageModel(file,price,condition,user_id);
                        buyList.add(buyModel);
                        swipeAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

}

}

适配器:

public class BuySwipeAdapter 扩展了 FragmentStatePagerAdapter {

private ArrayList<BuyHorizontalPageModel> buySet;
FragmentManager fm;
//SparseArray<Fragment> registeredFragment = new SparseArray<>();


public BuySwipeAdapter(FragmentManager fm,ArrayList<BuyHorizontalPageModel> buySet) {
    super(fm);
    this.buySet = buySet;
    this.fm = fm;

}

@Override
public Fragment getItem(int position) {

    BuyHorizontalPageModel pageSet = buySet.get(position);
    Fragment pageFragment = new FragmentPage();
    final Bundle bundle = new Bundle();
    bundle.putString("price",pageSet.getPrice());
    bundle.putString("condition",pageSet.getCondition());
    bundle.putString("user_id",pageSet.getUser_id());
    ParseFile file = pageSet.getFile();

    try {
        byte[] imageData = file.getData();
        bundle.putByteArray("book_image",imageData);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    pageFragment.setArguments(bundle);
    return pageFragment;
}

@Override
public int getCount() {
    return buySet.size();
}

片段:

public class FragmentPage 扩展片段 {

ImageView book_image;
CircleImageView profile_user;
TextView price,condition;
String user;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.buy_items,container,false);
    book_image = (ImageView)view.findViewById(R.id.book_image);
    profile_user = (CircleImageView)view.findViewById(R.id.profile_image);
    price = (TextView)view.findViewById(R.id.price);
    condition = (TextView)view.findViewById(R.id.condition);


    // retrieve Bundle
    Bundle bundle = getArguments();
    String priceBook = bundle.getString("price");
    String conditionBook = bundle.getString("condition");
    String user_id = bundle.getString("user_id");
    byte[] data = bundle.getByteArray("book_image");
    Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
    book_image.setImageBitmap(bitmap);

    ParseQuery<ParseObject> query = ParseQuery.getQuery("FbUser");
    query.whereEqualTo("user_id",user_id);
    query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            if(e==null){
                for (ParseObject object : objects){
                    ParseFile file = object.getParseFile("user_image");
                    file.getDataInBackground(new GetDataCallback() {
                        @Override
                        public void done(byte[] data, ParseException e) {
                            Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
                            profile_user.setImageBitmap(bitmap);
                        }
                    });
                }
            }
        }
    });
    //byte[] data = bundle.getByteArray("book_image");
    //Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
    //book_image.setImageBitmap(bitmap);

    price.setText("₹" + priceBook);
    price.setTextSize(20);
    condition.setText(conditionBook);
    condition.setTextSize(15);

    return view;
}

}

你只需要把线 viewPager.setCurrentItem(pos); 设置 viewpager 适配器后和设置后 setOffscreenPageLimit

这是因为在设置当前项后,你在设置适配器,导致之前设置的当前项被擦掉