我试图让swipe view表现得像Pinterest。最初正在滑动工作,我想知道在第一次滑动之后,该位置将始终回到位置1.
请提供一些建议。在此先感谢您的帮助。 :)
以下是活动类:
public class ProductV2Activity extends FragmentActivity
{
protected Integer productId;
protected Integer prdPosition;
protected ArrayList<String> productIdArray;
protected String pageArg;
protected Integer productIdArraySize;
protected static Integer NUM_ITEMS;
protected ViewPager viewPager;
protected ProductV2FragmentPageAdapter productV2FragmentPageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.product_v2_activity);
// Get product id, product position and product ID Array passed from ExploreFragment.java
Bundle extras = this.getIntent().getExtras();
this.productId = extras.getInt("target_product_id");
this.prdPosition = extras.getInt("position");
this.productIdArray = extras.getStringArrayList("productIdArray");
this.pageArg = extras.getString("page_argument");
this.productIdArraySize = productIdArray.size();
// Initialise ViewPager
viewPager = (ViewPager) findViewById(R.id.pager);
// Get ProductID array size
NUM_ITEMS = productIdArray.size();
// Calling inner class function to initialize adapter and
// setAdapter()
initializeAdapter(prdPosition);
// set number of page instances(fragment) to kept in memory
viewPager.setOffscreenPageLimit(1);
// make a trick by making padding between pages inside view-pager
// fill-in the padding with black color
viewPager.setPageMargin(60);
viewPager.setPageMarginDrawable(R.color.black);
this.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
int prevPage = prdPosition;
@Override
public void onPageSelected(int position) {
int newPosition = 0;
// Detect swipe gesture to right or left
// Move to Right
if (position-1 == prevPage)
{
System.out.println("Swipe-Direction : Move to RIGHT (+1) " + position);
prevPage = position;
}
// Move to Left
if (position +1 == prevPage)
{
System.out.println("Swipe-Direction : Move to LEFT (-1) " + position);
prevPage = position;
}
// reinitialize adapter to create a new fragment
initializeAdapter(position);
System.out.println("Swipe-Direction :- Current Position : " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* Function to initialise and setAdapter for
*/
private void initializeAdapter(int position)
{
Integer newProductId = Product.ProductStoredID.getProductIdOnPosition(position, pageArg);
// initialize adapter
productV2FragmentPageAdapter = new ProductV2FragmentPageAdapter(getSupportFragmentManager(), newProductId, position);
viewPager.setAdapter(productV2FragmentPageAdapter);
// displaying selected Product based on its position
viewPager.setCurrentItem(position);
}
/**
* A simple pager adapter that represents product {@link ProductV2SlidePageFragment} objects, in
* sequence.
*
* FragmentStatePagerAdapter consumes less memory, it's perfect in the case where number of pages is high or undetermined
*/
private class ProductV2FragmentPageAdapter extends FragmentStatePagerAdapter
{
private int productID;
private int productPosition;
public ProductV2FragmentPageAdapter(FragmentManager fm, Integer productId, Integer prdPosition) {
super(fm);
this.productID = productId;
this.productPosition = prdPosition;
}
@Override
// This method returns the fragment associated with
// the specific position
//
// It is called when the Adapter needs a fragment
// and it does not exists
public Fragment getItem(int position) {
return ProductV2SlidePageFragment.create(productPosition, productID);
}
@Override
public int getCount() {
return NUM_ITEMS;
}
} // private class ProductV2FragmentPageAdapter extends FragmentStatePagerAdapter
}
这是片段:
public class ProductV2SlidePageFragment extends Fragment implements View.OnClickListener, HttpRequestInterface
{
public static final String position = "current_fragment_position";
public static final String product_id = "this_product_id";
protected static final String PRODUCT_DETAIL_CALLER = "get_product_detail";
protected static final String PRODUCT_DETAIL_SAVED_COLLECTION = "get_who_saved_this_collection";
protected static final String PRODUCT_DETAIL_NEXT_CALLER = "get_next_product_detail_contents";
protected static final String SET_LOVE_PRODUCT = "love_unlove_product";
protected Integer mPageNumber;
protected static final String VIEW_MORE_IMAGES = "view_more_product_images";
protected static final String VIEW_STORE = "view_store";
protected static final String VIEW_PROFILE = "view_profile";
protected static final String LOVE_ITEM = "love_favorite_item";
protected static final String SAVE_ITEM = "save_favorite_item";
protected static final String SHARE_ITEM = "share_favorite_item";
protected static final String DETAILS_ROW = "get_more_details_info_table_row";
protected static final String SHIPPING_ROW = "get_shipping_info_details_table_row";
protected static final String BACK = "click_back";
protected LinearLayout fullPageLayout;
protected RelativeLayout middleContentLayout;
protected RelativeLayout storeInfoLayout;
protected Activity activity;
protected Integer productId;
protected Integer prd_ownerid;
protected Boolean isProfileOwner;
protected Boolean isUserLoggedIn;
protected Integer targetUserId;
protected Integer uid = 0;
protected User user;
protected Button pinterestButton;
protected RelativeLayout moreProductImagesLayout;
protected LinearLayout arrowBackButton;
protected LinearLayout loveButton;
protected LinearLayout savesButton;
protected LinearLayout shareButton;
protected Button addToCartButton;
protected Button inCartButton;
protected Button disableAddToCartButton;
protected Button addToCartButtonTwo;
protected Button inCartButtonTwo;
protected Button disableAddToCartButtonTwo;
protected LinearLayout viewStoreButton;
protected LinearLayout viewProfileButton;
protected RelativeLayout storeLayoutButton;
protected TextView moreImageNumText;
protected TextView loveText;
protected TextView lovedText;
protected ImageView loveImage;
protected ImageView lovedImage;
protected ImageView primaryProductImage;
protected TextView productName;
protected TextView productPrice;
protected TextView quantityAvailable;
protected ProductVariation productVariation;
protected LinearLayout productVariationSection;
protected LinearLayout firstSpinnerLayout;
protected LinearLayout secondSpinnerLayout;
protected TextView productDetailsDesc;
protected LinearLayout prdDetailsDescRow;
protected Boolean showMoreFlag = false;
protected ImageView arrowShowMore;
protected ImageView arrowShowLess;
protected TableRow shippingInfoLayout;
protected TableLayout shippingPriceLayout;
protected TextView shippingInfoDetails;
protected Boolean showMoreShippingInfoFlag = false;
protected ImageView arrowShowMoreShipping;
protected ImageView arrowShowLessShipping;
protected List<Product.ProductShipping> productShippingList = new ArrayList<>();
protected ImageView storeAvatarImg;
protected TextView storeName;
protected TextView storeItemCount;
protected GridView productItemGridView;
protected ProductDetailsV2Adapter adapter;
protected SortedMap<Integer, ProductPicked.ProductPickedLite> productItemList = new TreeMap<>();
protected RelativeLayout savedCollection;
protected GridView savedCollectionListView;
protected SavedCollectionAdapter savedCollectionAdapter;
protected ArrayList<Product.whoSavedCollections> savedCollectionList = new ArrayList<>();
protected RelativeLayout productTagsLayout;
protected ArrayList<String> tagNameList = new ArrayList<>();
protected ListView productTagsListView;
protected RelativeLayout similarItemsLayout;
protected GridView similarItemsGridView;
protected ArrayList<Product.ProductSimilarItems> similarItemList = new ArrayList<>();
protected FrameLayout progressBarLayout;
protected ProgressBar progressBar;
protected ProgressBar loveUnloveProgressBar;
protected RelativeLayout bottomProgressBar;
protected LinearLayout loveUnloveLayout;
protected Boolean isUpdateRequired = true;
protected PullToRefreshLayout pullToRefreshLayout;
protected RatingBar ratingBar;
protected TextView rateInFraction;
protected TextView totalReviews;
public static ProductV2SlidePageFragment create(int pageNumber,int productId)
{
ProductV2SlidePageFragment fragment = new ProductV2SlidePageFragment();
Bundle args = new Bundle();
args.putInt(position, pageNumber);
args.putInt(product_id, productId);
fragment.setArguments(args);
return fragment;
}
public void onAttach(Activity act)
{
super.onAttach(act);
activity = act;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(position);
productId = getArguments().getInt(product_id);
this.user = User.getLoggedInUser();
this.isUserLoggedIn = (this.user != null);
if (isUserLoggedIn) {
this.uid = user.getUid();
}
this.isProfileOwner = (this.uid.equals(targetUserId));
this.adapter = new ProductDetailsV2Adapter(activity, productItemList);
this.savedCollectionAdapter = new SavedCollectionAdapter(activity,savedCollectionList);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
final View swipeView = inflater.inflate(R.layout.product_v2_screen_slide_page, container, false);
this.fullPageLayout = (LinearLayout) swipeView.findViewById(R.id.full_layout_container);
this.middleContentLayout = (RelativeLayout) swipeView.findViewById(R.id.product_detail_middle_section);
this.storeInfoLayout = (RelativeLayout) swipeView.findViewById(R.id.store_info_layout);
this.primaryProductImage = (ImageView) swipeView.findViewById(R.id.primary_product_image);
this.moreImageNumText = (TextView) swipeView.findViewById(R.id.multiple_image_number);
this.loveText = (TextView) swipeView.findViewById(R.id.love_textview);
this.lovedText = (TextView) swipeView.findViewById(R.id.loved_textview);
this.loveImage = (ImageView) swipeView.findViewById(R.id.love_pink_icon);
this.lovedImage = (ImageView) swipeView.findViewById(R.id.love_fully_pink_icon);
this.productName = (TextView) swipeView.findViewById(R.id.product_name);
this.productPrice = (TextView) swipeView.findViewById(R.id.product_price);
this.quantityAvailable = (TextView) swipeView.findViewById(R.id.prd_available_quantity);
this.productVariationSection = (LinearLayout) swipeView.findViewById(R.id.product_variation_section);
this.firstSpinnerLayout = (LinearLayout) swipeView.findViewById(R.id.first_spinner_layout);
this.secondSpinnerLayout = (LinearLayout) swipeView.findViewById(R.id.second_spinner_layout);
this.pinterestButton = (Button) swipeView.findViewById(R.id.pinterest_button);
this.moreProductImagesLayout = (RelativeLayout) swipeView.findViewById(R.id.view_more_images_layout);
this.arrowBackButton = (LinearLayout) swipeView.findViewById(R.id.arrow_left_back_layout);
this.loveButton = (LinearLayout) swipeView.findViewById(R.id.love_button);
this.savesButton = (LinearLayout) swipeView.findViewById(R.id.save_button);
this.shareButton = (LinearLayout) swipeView.findViewById(R.id.share_button);
this.addToCartButton = (Button) swipeView.findViewById(R.id.prd_detail_btn_add_to_cart);
this.inCartButton = (Button) swipeView.findViewById(R.id.prd_detail_btn_in_cart);
this.disableAddToCartButton = (Button) swipeView.findViewById(R.id.prd_detail_btn_add_to_cart_disable);
this.addToCartButtonTwo = (Button) swipeView.findViewById(R.id.prd_detail_btn_add_to_cart_two);
this.inCartButtonTwo = (Button) swipeView.findViewById(R.id.prd_detail_btn_in_cart_two);
this.disableAddToCartButtonTwo = (Button) swipeView.findViewById(R.id.prd_detail_btn_add_to_cart_disable_two);
this.viewStoreButton = (LinearLayout) swipeView.findViewById(R.id.view_store_btn);
this.viewProfileButton = (LinearLayout) swipeView.findViewById(R.id.view_profile_btn);
this.storeLayoutButton = (RelativeLayout) swipeView.findViewById(R.id.store_info_details);
this.productDetailsDesc = (TextView) swipeView.findViewById(R.id.details_description);
this.prdDetailsDescRow = (LinearLayout) swipeView.findViewById(R.id.detail_desc_with_arrow_layout); // 'Details' table row that enable to click for more details
this.shippingInfoLayout = (TableRow) swipeView.findViewById(R.id.shipping_second_row); // 'Shipping' table row that enable to click for more details
this.shippingPriceLayout = (TableLayout) swipeView.findViewById(R.id.shipping_price_layout);
this.arrowShowMore = (ImageView) swipeView.findViewById(R.id.arrow_down_show_more);
this.arrowShowLess = (ImageView) swipeView.findViewById(R.id.arrow_up_show_less);
this.arrowShowMoreShipping = (ImageView) swipeView.findViewById(R.id.shipping_arrow_down_show_more);
this.arrowShowLessShipping = (ImageView) swipeView.findViewById(R.id.shipping_arrow_up_show_less);
this.shippingInfoDetails = (TextView) swipeView.findViewById(R.id.shipping_info_description);
this.storeAvatarImg = (ImageView) swipeView.findViewById(R.id.store_image);
this.storeName = (TextView) swipeView.findViewById(R.id.prd_detail_store_name);
this.storeItemCount = (TextView) swipeView.findViewById(R.id.prd_detail_store_item_count);
this.productItemGridView = (GridView) swipeView.findViewById(R.id.prd_item_grid_view);
this.productItemGridView.setAdapter(adapter);
this.productItemGridView.setFocusable(false);
this.progressBarLayout = (FrameLayout) swipeView.findViewById(R.id.product_details_progress_bar_layout);
this.progressBar = (ProgressBar) swipeView.findViewById(R.id.product_details_progress_bar);
this.loveUnloveProgressBar = (ProgressBar) swipeView.findViewById(R.id.love_unlove_progress_bar);
this.bottomProgressBar = (RelativeLayout) swipeView.findViewById(R.id.bottom_progress_bar_layout);
this.loveUnloveLayout = (LinearLayout) swipeView.findViewById(R.id.love_unlove_layout);
this.ratingBar = (RatingBar) swipeView.findViewById(R.id.rating_bar);
this.rateInFraction = (TextView) swipeView.findViewById(R.id.rating_result);
this.totalReviews = (TextView) swipeView.findViewById(R.id.rating_reviews);
this.savedCollection = (RelativeLayout) swipeView.findViewById(R.id.who_saved_this_container);
this.savedCollectionListView = (GridView) swipeView.findViewById(R.id.saved_collection_list_view);
this.savedCollectionListView.setAdapter(savedCollectionAdapter);
this.moreProductImagesLayout.setTag(VIEW_MORE_IMAGES);
this.viewStoreButton.setTag(VIEW_STORE);
this.viewProfileButton.setTag(VIEW_PROFILE);
this.storeLayoutButton.setTag(VIEW_STORE);
this.loveButton.setTag(LOVE_ITEM);
this.savesButton.setTag(SAVE_ITEM);
this.shareButton.setTag(SHARE_ITEM);
this.arrowBackButton.setTag(BACK);
this.prdDetailsDescRow.setTag(DETAILS_ROW);
this.shippingInfoLayout.setTag(SHIPPING_ROW);
this.moreProductImagesLayout.setOnClickListener(this);
this.viewStoreButton.setOnClickListener(this);
this.viewProfileButton.setOnClickListener(this);
this.storeLayoutButton.setOnClickListener(this);
this.loveButton.setOnClickListener(this);
this.savesButton.setOnClickListener(this);
this.shareButton.setOnClickListener(this);
this.prdDetailsDescRow.setOnClickListener(this);
this.shippingInfoLayout.setOnClickListener(this);
this.arrowBackButton.setOnClickListener(this);
LoadProductDetailsAsynTask task = new LoadProductDetailsAsynTask(productId, false);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return swipeView;
}
@Override
public void onClick(View v)
{
String tag = (String) v.getTag();
switch (tag)
{
// onclick performance
}
}
public void ProductDetailsSavedCollectionRequest(int product_id)
{
Integer productId = product_id;
String uid = "";
String accessKey = "";
String baseUrl = Utility.getBaseUrl(activity.getApplicationContext());
if(isUserLoggedIn){
uid = user.getUid().toString();
accessKey = user.getAccessKey();
}
List<NameValuePair> gParams = new ArrayList<>();
gParams.add(new BasicNameValuePair("api_key", Utility.getPublicKey()));
gParams.add(new BasicNameValuePair("caller", PRODUCT_DETAIL_SAVED_COLLECTION));
gParams.add(new BasicNameValuePair("uid", uid));
gParams.add(new BasicNameValuePair("access_key", accessKey));
gParams.add(new BasicNameValuePair("productId", productId.toString()));
HttpRequestController httpClient = new HttpRequestController(ProductV2SlidePageFragment.this);
String httpURL = "http://" + baseUrl +"/mobile/js/android/v1/product_v2/get_product_details_saved_collection";
httpClient.performAsynRequest(httpURL, gParams);
}
public void ProductDetailsNextRequest(int product_id, int product_nid, int cat)
{
Integer productId = product_id;
Integer productNID = product_nid;
Integer category = cat;
String uid = "";
String accessKey = "";
String baseUrl = Utility.getBaseUrl(activity.getApplicationContext());
if(isUserLoggedIn){
uid = user.getUid().toString();
accessKey = user.getAccessKey();
}
List<NameValuePair> gParams = new ArrayList<>();
gParams.add(new BasicNameValuePair("api_key", Utility.getPublicKey()));
gParams.add(new BasicNameValuePair("caller", PRODUCT_DETAIL_NEXT_CALLER));
gParams.add(new BasicNameValuePair("access_key", accessKey));
gParams.add(new BasicNameValuePair("productId", productId.toString()));
gParams.add(new BasicNameValuePair("productNid", productNID.toString()));
gParams.add(new BasicNameValuePair("category", category.toString()));
HttpRequestController httpClient = new HttpRequestController(ProductV2SlidePageFragment.this);
String httpURL = "http://" + baseUrl +"/mobile/js/android/v1/product_v2/get_product_details_next_contents";
httpClient.performAsynRequest(httpURL, gParams);
bottomProgressBar.setVisibility(View.VISIBLE);
}
private class LoadProductDetailsAsynTask extends AsyncTask<Void, Void, Void>
{
Integer productId;
String baseUrl;
Boolean isForceRefresh;
String uid = "";
String accessKey = "";
public LoadProductDetailsAsynTask(Integer productId, Boolean isForceRefresh)
{
this.productId = productId;
this.baseUrl = Utility.getBaseUrl(activity.getApplicationContext());
this.isForceRefresh = isForceRefresh;
if(isUserLoggedIn){
this.uid = user.getUid().toString();
this.accessKey = user.getAccessKey();
}
}
@Override
protected Void doInBackground(Void... params)
{
List<NameValuePair> gParams = new ArrayList<>();
gParams.add(new BasicNameValuePair("api_key", Utility.getPublicKey()));
gParams.add(new BasicNameValuePair("caller", PRODUCT_DETAIL_CALLER));
gParams.add(new BasicNameValuePair("uid", uid));
gParams.add(new BasicNameValuePair("access_key", accessKey));
gParams.add(new BasicNameValuePair("productId", productId.toString()));
gParams.add(new BasicNameValuePair("provider_type", "hugerect"));
HttpRequestController httpClient = new HttpRequestController(ProductV2SlidePageFragment.this);
String httpURL = "http://" + baseUrl +"/mobile/js/android/v1/product_v2/get_product_details";
httpClient.performAsynRequest(httpURL, gParams);
return null;
}
}
@Override
public void HttpRequestPreExecute(String caller) {
}
@Override
public void HttpRequestDoInBackground(HttpReturnObject response) {
}
@Override
public void HttpRequestDoInBackgroundError(HttpReturnObject response) {
}
@Override
public void HttpRequestProgressUpdate(HttpReturnObject response) {
}
@Override
public void HttpRequestOnPostExecuteUpdate(HttpReturnObject response)
{
try
{
JSONObject responseJson = response.getJSON();
Integer statusCode = responseJson.getInt("status_code");
switch (statusCode)
{
case 200:
JSONObject returnVars = responseJson.getJSONObject("return_vars");
String caller = responseJson.getString("caller");
if(!returnVars.has("error"))
{
switch (caller)
{
case PRODUCT_DETAIL_CALLER:
{
// Get all JSON data and
// display details
break;
}
case PRODUCT_DETAIL_SAVED_COLLECTION:
{
// Get all JSON data and
// display details
break;
}
case PRODUCT_DETAIL_NEXT_CALLER:
{
// Get all JSON data and
// display details
break;
}
case SET_LOVE_PRODUCT:
{
break;
}
break;
case 403:
default:
Toast.makeText(activity, "You do not have permission to perform this action.", Toast.LENGTH_LONG).show();
break;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void createSnackBar(Snackbar snackbar)
{
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
layout.setBackgroundColor(Color.parseColor("#F50057"));
TextView snackBarText = (TextView) layout.findViewById(android.support.design.R.id.snackbar_text);
snackBarText.setTextColor(getResources().getColor(R.color.white));
snackBarText.setTextSize(16);
snackBarText.setGravity(Gravity.CENTER_HORIZONTAL);
snackbar.show();
}
private void setProductRating(double totalRating, Integer totalReview)
{
LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
String reviews = "("+totalReview+" reviews)";
String rate = totalRating+" / 5";
ratingBar.setRating((float) totalRating);
rateInFraction.setText(rate);
totalReviews.setText(reviews);
}
private class ProductDetailsV2Adapter extends BaseAdapter
{
private SortedMap<Integer,ProductPicked.ProductPickedLite> data;
private LayoutInflater inflater;
private ImageHandler image;
public ProductDetailsV2Adapter(Activity activity, SortedMap<Integer, ProductPicked.ProductPickedLite> productItemList)
{
this.data = productItemList;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.image = new ImageHandler(activity, ImageHandler.ScaleType.PICKED_PRODUCT);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
public String getProductImage(int position)
{
return data.get(position).getImageSource();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.grid_view_image);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
String prdImageSource = getProductImage(position);
holder.imageView.setTag(prdImageSource);
image.displayImage(prdImageSource, holder.imageView, null);
return convertView;
}
public class ViewHolder
{
ImageView imageView;
}
public void setMap(SortedMap<Integer,ProductPicked.ProductPickedLite> d)
{
data = d;
}
}
}