viewPager中图像的水平滚动视图

时间:2015-11-25 06:44:05

标签: android xml horizontal-scrolling

image

我希望这个水平滚动视图在视图寻呼机中像flipkart一样滑动。任何人都可以帮我解决这个问题。我做了一个编码,因为我只能刷一个图像。 目前我只使用静态图像。稍后我会解析

1 个答案:

答案 0 :(得分:0)

我已经创建了一个图像滑块,它将使用picasso.Due从服务器加载图像到时间不足我发布示例的完整代码,您可以轻松地修改它:)

enter image description here

<强> post_item_viewer

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <RelativeLayout
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_height"
        android:background="@color/base_color">

        <ImageView
            android:id="@+id/close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:src="@drawable/abc_ic_clear_mtrl_alpha" />

        <TextView
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="20dp"
            android:layout_toEndOf="@+id/close"
            android:layout_toRightOf="@+id/close"
            android:textColor="@color/white"
            android:textSize="@dimen/heading_text" />
    </RelativeLayout>


    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        android:layout_marginBottom="@dimen/footer_height"></android.support.v4.view.ViewPager>

    <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="@dimen/footer_height"
        android:layout_alignParentBottom="true"
        android:background="@color/black">

        <ImageView
            android:id="@+id/prev"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="30dp"
            android:src="@drawable/ic_arrowleft" />

        <TextView
            android:id="@+id/image_position"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="0  of  0"
            android:textColor="@color/white"
            android:textSize="@dimen/heading_text" />

        <ImageView
            android:id="@+id/next"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="30dp"
            android:src="@drawable/ic_arrowright" />
    </RelativeLayout>
</RelativeLayout>

<强> UserPostViewer

public class UserPostViewer extends DialogFragment implements View.OnClickListener {
    private ProgressDialog progressDialog;
    private View view;
    private int position = 0;
    private ImageView mNext;
    private ImageView mPrevious;
    private ViewPager viewPager;
    private int COUNT_MAX = 0;
    private final int COUNT_MIN = 0;
    private MaterialTextViewMedium mPosView;
    private MaterialTextViewMedium title;

    /**
     * Create a new instance of UserPostViewer, providing "userId" and "userName"
     * as arguments.
     */
    static UserPostViewer newInstance(String userId, String userName) {
        UserPostViewer fragment = new UserPostViewer();
        Bundle args = new Bundle();
        args.putString("user_id", userId);
        args.putString("user_name", userName);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int style = DialogFragment.STYLE_NO_TITLE, theme = android.R.style.Theme_Holo_Light;
        setStyle(style, theme);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.post_item_viewer, container, false);
        initProgressDialog();
        closeListener();
        String userId = getArguments().getString("user_id");
        Map<String, String> params = new HashMap<>();
        params.put("user_id", userId);
        getPosts(params);
        return view;
    }

    private void initProgressDialog() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
    }

    private void showProgressDialog(String message) {
        if (!progressDialog.isShowing())
            progressDialog.setMessage(message);
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }

    private void getPosts(Map<String, String> params) {
        VolleyJsonArrayReq arrayReq = new VolleyJsonArrayReq (Constants.USER_IMAGES, new JSONObject(params), new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                try {
                    if (response != null) {
                        Gson gson = new Gson();
                        Type collectionType = new TypeToken<Collection<GetPostItems>>() {
                        }.getType();
                        Collection<GetPostItems> getPostItemses = gson.fromJson(response.toString(), collectionType);
                        initView(getPostItemses);
                    }
                } catch (Exception e) {
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                hideProgressDialog();
                if (getActivity() != null && isAdded()) {
                    String errorString = VolleyErrorHelper.getMessage(error, getActivity());
                    if (errorString != null) {
                        Util.showAlert(getActivity(), getResources().getString(R.string.error), errorString);
                    }
                }
            }
        });
        showProgressDialog(getResources().getString(R.string.loading));
         CustomVolleyHelper.getInstance(getActivity()).addToRequestQueue(arrayReq);
    }

    private void initView(Collection<GetPostItems> mGetPostItemses) {
        try {
            if (view != null && getActivity() != null) {
                String userName = getArguments().getString("user_name");
                viewPager = (ViewPager) view.findViewById(R.id.pager);
                title = (MaterialTextViewMedium) view.findViewById(R.id.username);
                title.setText(getResources().getString(R.string.title_support) + userName);
                mPosView = (MaterialTextViewMedium) view.findViewById(R.id.image_position);
                viewPager.setPageTransformer(true, new DepthPageTransformer());
                mNext = (ImageView) view.findViewById(R.id.next);
                mPrevious = (ImageView) view.findViewById(R.id.prev);
                List<GetPostGridItems> mItems = new ArrayList<>();
                for (GetPostItems getPostItemses : mGetPostItemses) {
                    GetPostGridItems getPostGridItems = new GetPostGridItems();
                    getPostGridItems.setThumbnail(Constants.BASE_URL + getPostItemses.getImage_path());
                    mItems.add(getPostGridItems);
                }
                COUNT_MAX = mItems.size() - 1;
                PostPagerAdapter adapter = new PostPagerAdapter(getActivity(), mItems);
                viewPager.setAdapter(adapter);
                setListener();
                updateView(COUNT_MIN);
            }
            hideProgressDialog();
        } catch (Exception e) {

        }
    }

    private void setListener() {
        viewPager.addOnPageChangeListener(onPageChangeListener);
        mNext.setOnClickListener(this);
        mPrevious.setOnClickListener(this);
    }

    private void closeListener() {
        ImageView closeDialog = (ImageView) view.findViewById(R.id.close);
        closeDialog.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next:
                if (position != COUNT_MAX) {
                    position++;
                    swipeTo(position);
                }
                break;
            case R.id.prev:
                if (position != COUNT_MIN) {
                    position--;
                    swipeTo(position);
                }
                break;
            case R.id.close:
                dismiss();
                break;

        }
    }

    ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int currentPosition) {
            position = currentPosition;
            updateView(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void swipeTo(int position) {
        viewPager.setCurrentItem(position, true);
        updateView(position);
    }


    private void updateView(int position) {
        mPosView.setText((position + 1) + "  of  " + (COUNT_MAX + 1));
    }


}

<强> PostPagerAdapter

public class PostPagerAdapter extends PagerAdapter {
    private final int THUMB_MAX_WIDTH = 250;//720
    private final int THUMB_MAX_HEIGHT = 250;//480
    private int size;
    private Context mContext;
    private List<GetPostGridItems> mItems;

    public PostPagerAdapter(Context context, List<GetPostGridItems> mItems) {
        this.size = (int) Math.ceil(Math.sqrt(THUMB_MAX_WIDTH * THUMB_MAX_HEIGHT));
        this.mContext = context;
        this.mItems = mItems;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        LayoutInflater mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = mLayoutInflater.inflate(R.layout.post_pager_item, container, false);
        ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
        Picasso.with(mContext)
                .load(mItems.get(position).getThumbnail()).placeholder(R.drawable.ic_profile_thumb).resize(size, size)
                .centerInside()
                .into(imageView);
        container.addView(itemView);
        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}

<强> post_pager_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

<强> GetPostGridItems

public class GetPostGridItems {

private String mThumbnail;

public String getThumbnail() {
        return mThumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.mThumbnail = thumbnail;
    }
}

显示图像滑块DialogFragment

 private void showDialog() {
        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            transaction.remove(prev);
        }
        transaction.addToBackStack(null);

        // Create and show the dialog.
        DialogFragment newFragment = UserPostViewer.newInstance(mUserId, mUserName);
        newFragment.show(transaction, "dialog");
    }

注意:从下方链接中找到动画所需的文件。

DepthPageTransformer