使用ViewPager和布局文件完成滑动切换

Posted buled

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用ViewPager和布局文件完成滑动切换相关的知识,希望对你有一定的参考价值。

1.首先是主页面的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/ii_lottery_category"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#f6f6f6"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/hot_list_Tv"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:gravity="center_horizontal"
            android:paddingBottom="14dp"
            android:text="a1"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/collection_list_Tv"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:gravity="center_horizontal"
            android:paddingBottom="14dp"
            android:text="a2"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/sales_list_Tv"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:gravity="center_horizontal"
            android:paddingBottom="14dp"
            android:text="a3"
            android:textSize="13sp" />
    </LinearLayout>

    <ImageView
        android:id="@+id/ii_category_selector"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="matrix"
        android:src="@drawable/id_category_selector"
         />

    <android.support.v4.view.ViewPager
        android:id="@+id/business_list_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF" 
        >
    </android.support.v4.view.ViewPager>

</LinearLayout>

2.然后是主页面的代码
public class MainActivity extends FragmentActivity implements OnClickListener
	/**
	 * 屏幕的宽度和高度
	 */
	public static int mScreenWidth;
	public static int mScreenHeight;
	private LinearLayout back_Iv;
	private ImageView selector; // 下划线
	private TextView hot_list_Tv;// 热门排行
	private TextView collection_list_Tv;// 收藏排行
	private TextView sales_list_Tv; // 销量排行
	private ViewPager viewPager;
	private BusinessRankAdapter pagerAdapter;
	private ArrayList<Fragment> pagers;

	private int currentPage = 0; // 当前viewpager页面
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById();
		setListener();
		init();
	

	protected void findViewById() 
		context = this;
		 /**
         * 获取屏幕宽度和高度
         */
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		mScreenWidth = metric.widthPixels;
		mScreenHeight = metric.heightPixels;
//		back_Iv = (LinearLayout) findViewById(R.id.back_Iv);
		selector = (ImageView) findViewById(R.id.ii_category_selector);
		 initSelector();
		hot_list_Tv = (TextView) findViewById(R.id.hot_list_Tv);
		hot_list_Tv.setSelected(true);
		collection_list_Tv = (TextView) findViewById(R.id.collection_list_Tv);
		sales_list_Tv = (TextView) findViewById(R.id.sales_list_Tv);
		viewPager = (ViewPager) findViewById(R.id.business_list_viewpager);
		viewPager.setCurrentItem(0);
	

	protected void setListener() 
//		back_Iv.setOnClickListener(this);
		hot_list_Tv.setOnClickListener(this);
		collection_list_Tv.setOnClickListener(this);
		sales_list_Tv.setOnClickListener(this);
		
		viewPager.setOnPageChangeListener(onPageChangeListener);
	

	private void init() 
		initPager();
		pagerAdapter = new BusinessRankAdapter(getSupportFragmentManager(),
				pagers);
		viewPager.setAdapter(pagerAdapter);

	

	private void initPager() 
		pagers = new ArrayList<Fragment>();
		// 热门排行
		BusinessHotSortFragment mBusinessHotSortFragment = new BusinessHotSortFragment();
		Bundle bundle1 = new Bundle();

		bundle1.putString("rankType", "1");
//		mBusinessHotSortFragment.setArguments(bundle1);

		pagers.add(mBusinessHotSortFragment);

		// 收藏排行
		BusinessHotSortFragment collectSortFragment = new BusinessHotSortFragment();
		Bundle bundle2 = new Bundle();

		bundle2.putString("rankType", "2");
//		mBusinessHotSortFragment.setArguments(bundle2);
		pagers.add(collectSortFragment);

		// 销量排行
		BusinessHotSortFragment saleSortFragment = new BusinessHotSortFragment();
		Bundle bundle3 = new Bundle();

		bundle3.putString("rankType", "3");
//		mBusinessHotSortFragment.setArguments(bundle3);
		pagers.add(saleSortFragment);

	

	/**
	 * 初始化下划线位置
	 */
	private void initSelector() 
		Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.id_category_selector);
		int bitmapWidth = bitmap.getWidth();
		int left = (mScreenWidth / 3 - bitmapWidth) / 2;
		Matrix matrix = new Matrix();
		matrix.postTranslate(left, 0);
		selector.setImageMatrix(matrix);
	

	/**
	 * viewpager滑动时间监听器
	 */
	private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() 

		@Override
		public void onPageSelected(int position) 
			hot_list_Tv.setSelected(false);
			collection_list_Tv.setSelected(false);
			sales_list_Tv.setSelected(false);
			switch (position) 
			case 0:
				hot_list_Tv.setSelected(true);

				break;
			case 1:
				collection_list_Tv.setSelected(true);

				break;
			case 2:
				sales_list_Tv.setSelected(true);

				break;
			
			TranslateAnimation animation = new TranslateAnimation(currentPage
					* mScreenWidth / 3, position
					* mScreenWidth / 3, 0, 0);
			animation.setFillAfter(true);
			animation.setDuration(200);
			selector.startAnimation(animation);
			currentPage = position;
		

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) 

		

		@Override
		public void onPageScrollStateChanged(int arg0) 

		
	;

	@Override
	public void onClick(View v) 
		switch (v.getId()) 
//		case R.id.back_Iv:
//			finish();
//			break;
		case R.id.hot_list_Tv://
			viewPager.setCurrentItem(0);
			break;
		case R.id.collection_list_Tv:
			viewPager.setCurrentItem(1);
			break;
		case R.id.sales_list_Tv:
			viewPager.setCurrentItem(2);

			break;
		default:
			break;
		
	

	public class BusinessRankAdapter extends FragmentPagerAdapter 

	    private ArrayList<Fragment> pagers;



	    public BusinessRankAdapter(FragmentManager fm, ArrayList<Fragment> list) 
	        super(fm);
	        this.pagers = list;

	    

	    @Override
	    public int getCount() 
	        return pagers.size();
	    

	    @Override
	    public Fragment getItem(int arg0) 
	        return pagers.get(arg0);
	    


	

3.单个 Fragment的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="页面一" 
        android:textSize="20sp"/>

</LinearLayout>
4.单个Fragment的代码,这个是大概的代码,可以自己改,大部分其实是不需要的

public class BusinessHotSortFragment extends Fragment implements View.OnClickListener 

//    private PullToRefreshListView mPullToRefreshListView;
    private Activity mActivity;
    private View layoutView;


//    private BusinessHotListAdapter businessHotListAdapter;// 热门排行


    private String currentCityCode;
    private String rankType;  //排行类型:1 热门排行 2 收藏排行 3 销量排行

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        //Log.d(TAG, "onCreateView");
        Bundle args = getArguments();
        if(null != args)
        
            rankType = args.getString("rankType");
//            LogUtils.i("test", "rankType: " + rankType);
        

        if (layoutView == null) 
            layoutView = inflater.inflate(R.layout.fragment, container, false); // 加载fragment布局
//            findViewById();

//            init();
//            setListener();
        

        // 缓存的rootView需要判断是否已经被加过parent,
        // 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) layoutView.getParent();
        if (parent != null) 
            parent.removeView(layoutView);
        
        return layoutView;
    

    @Override
    public void onAttach(Activity activity) 
        super.onAttach(activity);
        mActivity = getActivity();
        //Log.d(TAG, "onAttach");
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        //Log.d(TAG, "onCreate");
    

	@Override
	public void onClick(View v) 
		// TODO Auto-generated method stub
		
	

//    @Override
//    protected void findViewById() 
//        mPullToRefreshListView = (PullToRefreshListView)layoutView.findViewById(R.id.business_sort_List);
//
//        // 上拉加载更多不可用
//        mPullToRefreshListView.setPullLoadEnabled(false);
//
//        // 滚动到底自动加载不可用
//        mPullToRefreshListView.setScrollLoadEnabled(true);
//    
//
//    @Override
//    protected void setListener() 
//        mPullToRefreshListView.setOnRefreshListener(listViewOnRefreshListener);
//        mPullToRefreshListView.getRefreshableView().setOnItemClickListener(
//                listViewOnItemClickListener);
//    
//
//    @Override
//    protected void init() 
//        currentCityCode = LocationUtil.getInstance().getCityId();
//        businessHotListAdapter = new BusinessHotListAdapter(mActivity);
//        //mListView = mPullToRefreshListView.getRefreshableView();
//
//        //mAdapter = new ShopCommentAdapter(ShopCommentListActivity.this);
//        mPullToRefreshListView.getListView().setAdapter(businessHotListAdapter);
//        mPullToRefreshListView.getListView().setDivider(null);
//        mPullToRefreshListView.doPullRefreshing(true, 0);
//    
//
//    /**
//     * 点击item跳转相应活动详情
//     */
//    AdapterView.OnItemClickListener listViewOnItemClickListener = new AdapterView.OnItemClickListener() 
//
//        @Override
//        public void onItemClick(AdapterView<?> parent, View view, int position,
//                                long id) 
//            BusinessListItemBean mBusinessListItemBean = businessHotListAdapter.getList().get(position);
//            String store_id = mBusinessListItemBean.getStore_id();
//            LogUtils.d(TAG, "热门排行" + " store_id=" + store_id);
//            if (!StringUtils.isBlank(store_id)) 
//                Intent intent = new Intent(mActivity, BusinessDetails.class);
//                intent.putExtra("shopId", store_id);
//                startActivity(intent);
//            
//
//
//
//        
//    ;
//    /**
//     * 上拉刷新,到底部自动加载
//     */
//
//    PullToRefreshBase.OnRefreshListener<ListView> listViewOnRefreshListener = new PullToRefreshBase.OnRefreshListener<ListView>() 
//
//        @Override
//        // 下拉松手后会被调用
//        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) 
//            if (businessHotListAdapter != null && businessHotListAdapter.getCount() > 0 && mPullToRefreshListView != null) 
//                mPullToRefreshListView.getRefreshableView().setSelection(0);// 回顶部
//            
//
//            requstBusinessList(Constant.REQUEST_REFRESH, String.valueOf(20));
//        
//
//        @Override
//        // 加载更多时会被调用或上拉时调用
//        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) 
//           // int pageIndex = (businessHotListAdapter.getCount() / Constant.PAGE_SIZE) + 1;
//
//
//           // requstBusinessList(Constant.REQUEST_ALL, shopId, pageIndex, Constant.PAGE_SIZE);
//        
//    ;
//    /**
//     *
//     * @param rueqestType
//     *
//     * @param limit 请求个数限制
//     */
//    private void requstBusinessList(final int rueqestType, String limit) 
//        LogUtils.i("test", "requstBusinessList begin");
//        // initProgressDialog();
//
//        HashMap<String, String> params = RequestParamsHelper.getBusinessList(currentCityCode, limit, rankType);
//        JsonObjectDefaultGetRequest req = new JsonObjectDefaultGetRequest(Urls.GET_BUSINESSLIST, params, new Response.Listener<JSONObject>() 
//            @Override
//            public void onResponse(JSONObject response) 
//
//                LogUtils.i("test", "热门排行response:" + response);
//                if (response != null) 
//                    Message msg = Message.obtain();
//
//                    BusinessListBean businessListBean = BusinessListBean.parse(response);
//                    if (businessListBean != null) 
//                        if (businessListBean.getSta().equals("1")) 
//                            List<BusinessListItemBean> lists = businessListBean.getLists();
//                            msg.what = Constant.HTTP_SUCCESS;
//                            msg.arg1 = Integer.valueOf(lists.size());
//                            LogUtils.i("test", "msg.arg1:" + msg.arg1);
//                            msg.arg2 = rueqestType;
//                            msg.obj = lists;
//                         else 
//
//                                String errorMsg = businessListBean.getMsg();
//                                //ToastUtils.showOnceLongToast(mActivity, businessListBean.getMsg());
//                                msg.obj = errorMsg;
//                                msg.what = Constant.HTTP_FAIL;
//
//                        
//                        UIHandler.sendMessage(msg);
//                    else
//                    
//                        UIHandler.sendEmptyMessage(Constant.HTTP_FAIL);
//                    
//                else
//                
//                    UIHandler.sendEmptyMessage(Constant.HTTP_FAIL);
//                
//            
//
//        , new Response.ErrorListener() 
//
//            @Override
//            public void onErrorResponse(VolleyError error) 
//                LogUtils.e(TAG, "VolleyError: " + error);
//                UIHandler.sendEmptyMessage(Constant.HTTP_FAIL);
//            
//        );
//        BaseApplication.getInstance().addToRequestQueue(req, this);
//
//    
//
//    private Handler UIHandler = new Handler() 
//        @Override
//        public void handleMessage(Message msg) 
//            super.handleMessage(msg);
//
//            switch (msg.what) 
//                case Constant.HTTP_SUCCESS:
//                    boolean hasMoreData = true;
//                    List<BusinessListItemBean> list = (List<BusinessListItemBean>) msg.obj;
//                    if (msg.arg2 == Constant.REQUEST_REFRESH) 
//                        businessHotListAdapter.clear();
//                    
//
//                    if (msg.arg1 > 0) 
//                        businessHotListAdapter.appendToList(list);
//                        if (msg.arg1 < Constant.PAGE_SIZE || msg.arg1 <= businessHotListAdapter.getCount()) 
//                            hasMoreData = false;
//                        
//                     else 
//                        hasMoreData = false;
//                    
//
//                    mPullToRefreshListView.onPullDownRefreshComplete();
//                    mPullToRefreshListView.onPullUpRefreshComplete();
//                    // true表示还有更多的数据,false表示没有更多数据了
//                    mPullToRefreshListView.setHasMoreData(hasMoreData);
//                    break;
//
//
//                case Constant.HTTP_DATA_EMPTY:// 当返回的数据为0时
//                    mPullToRefreshListView.onPullDownRefreshComplete();
//                    mPullToRefreshListView.onPullUpRefreshComplete();
//                    // true表示还有更多的数据,false表示没有更多数据了
//                    businessHotListAdapter.clear();
//                    mPullToRefreshListView.setHasMoreData(false);
//                    mPullToRefreshListView.setNotNavilableData();
//                    break;
//                case Constant.NETWORK_ERROR_MSG:
//                    mPullToRefreshListView.onPullDownRefreshComplete();
//                    mPullToRefreshListView.onPullUpRefreshComplete();
//                    String errorMsg = (String) msg.obj;
//                    if (!StringUtils.isEmpty(errorMsg)) 
//                        ToastUtils.showOnceToast(mActivity, errorMsg);
//                    
//                    break;
//                case Constant.HTTP_FAIL:
//                    mPullToRefreshListView.onPullDownRefreshComplete();
//                    mPullToRefreshListView.onPullUpRefreshComplete();
//                    mPullToRefreshListView.setNetworkError();
//                    ToastUtils.showOnceToast(mActivity, getString(R.string.network_error));
//                    break;
//            
//        
//    ;
//    @Override
//    public void onClick(View v) 
//
//    





以上是关于使用ViewPager和布局文件完成滑动切换的主要内容,如果未能解决你的问题,请参考以下文章

ViewPager 滑动不适用于 RecyclerView

Android中仿淘宝商品详情ViewPager页面数据手动滑动

Adapter类控件使用之ViewPager(视图滑动切换工具)的基本使用

ViewPager实现页面切换

Android零基础入门第70节:ViewPager轻松完成TabHost效果

android怎么viewpager实现循环切换图片