viewpager和滑动下游标

本文详细介绍了一款Android应用的布局设计与实现过程,重点介绍了使用LinearLayout和RelativeLayout进行UI布局的方法,并通过ViewPager实现了流畅的页面切换效果。文章还涉及了自定义View、事件监听、Fragment管理和适配器开发等内容。
摘要由CSDN通过智能技术生成

先看布局文件

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/top_layout_height"
        android:background="@color/top_background_color"
        android:id="@+id/top_bar">

        <RelativeLayout
            android:id="@+id/select_city_Rlty"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@drawable/btn_red_top_selector"
            android:minWidth="62.0dip">

            <TextView
                android:id="@+id/select_city_Tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp"
                android:gravity="center"
                android:text="深圳"
                android:textColor="@color/white"
                android:textSize="18sp" />

            <ImageView
                android:id="@+id/icon_small_triangle_Iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@+id/select_city_Tv"
                android:src="@drawable/icon_home_city_down_arrow" />
        </RelativeLayout>

        <LinearLayout
            android:id="@+id/tab_ly"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/select_city_Rlty"
            android:layout_toLeftOf="@+id/search_Iv"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp">

            <TextView
                android:id="@+id/home"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:textColor="@drawable/bg_main_list_tv"
                android:textSize="18sp"
                android:padding="5dp"
                android:text="首页" />

            <View
                android:layout_width="0.5dp"
                android:layout_height="20dp"
                android:layout_gravity="center_vertical"
                android:background="@color/white" />

            <TextView
                android:id="@+id/club_card"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@drawable/bg_main_list_tv"
                android:textSize="18sp"
                android:padding="5dp"
                android:gravity="center"
                android:text="会员卡" />

            <View
                android:layout_width="0.5dp"
                android:layout_height="20dp"
                android:layout_gravity="center_vertical"
                android:background="@color/white" />

            <TextView
                android:id="@+id/my"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:textColor="@drawable/bg_main_list_tv"
                android:textSize="18sp"
                android:padding="5dp"
                android:text="我的" />
        </LinearLayout>

        <ImageView  //这里就是下游标,这个宽度一定要跟tab一样宽,而且不能自适应,不然一开始初始化移动位置的时候移动不了
            android:layout_alignLeft="@+id/tab_ly"
            android:layout_alignRight="@+id/tab_ly"
            android:layout_alignParentBottom="true"
            android:id="@+id/ii_category_selector"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="matrix"
            android:src="@drawable/menu_line"
            />

        <ImageView
            android:id="@+id/search_Iv"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="16dp"
            android:background="@drawable/btn_red_top_selector"
            android:src="@drawable/btn_search_selector" />
    </RelativeLayout>


    <com.dld.common.view.ArcMenu
        android:id="@+id/arc_menu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="72dp"
        android:layout_marginRight="8dp"
        android:visibility="gone" />-->

</LinearLayout>

2.然后看下代码,其实就是写了一个viewpeager

public class MainActivity extends BaseFragmentActivity implements OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int MAXTIME = 120000;// 倒计时最大时间
    private static final int INTERVAL = 1000;// 倒计时的时间间隔

    public static int curentlay = 0;
    private long exitTime = 0;
    // 监听HOME键
    private HomeKeyEventBroadCastReceiver mHomeKeyEventBroadCastReceiver;
    private ScreenBroadCastReceiver mScreenBroadCastReceiver;
    private RecommendDialog mRecommendDialog;
    private DldDBHelper mDldDBHelper = null;
    private Dao<MovieCityData, Integer> movieCityDao;
    private List<MovieCityBean> mCityList = new ArrayList<MovieCityBean>();
    private ArrayList<HashMap<String, String>> mCityIdList = new ArrayList<HashMap<String, String>>();
    //新
    private boolean hasMeasured = false;
    private float height;
    private float width;
    private ViewPager viewPager;
    private BusinessRankAdapter pagerAdapter;
    private ArrayList<Fragment> pagers;
    private RelativeLayout select_city_Rlty;// 选择城市
    private TextView select_city_Tv;// 选择城市
    private ImageView search_Iv;// 搜索
    private ImageView selector; // 下划线
    private LinearLayout tab_ly;
    private TextView home;// 首页
    private TextView card;// 会员卡
    private TextView my; // 我的
    private RelativeLayout topbar;//头部
    private Handler hd=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            initSelector();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //isSlideFinish = false;
        super.onCreate(savedInstanceState);
        // requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置无标题模式
        // setContentView(R.layout.activity_main_fragment_tabs); //
        // Activity样式文件,一定要写在中间
        setContentView(R.layout.activity_myfragmenttest);
        findViewById();
        init();
        setListener();
    }

    @Override
    protected void findViewById() {
        topbar= (RelativeLayout) this.findViewById(R.id.top_bar);
        select_city_Rlty = (RelativeLayout) this.findViewById(R.id.select_city_Rlty);
        select_city_Tv = (TextView) this
                .findViewById(R.id.select_city_Tv);
        search_Iv = (ImageView) this.findViewById(R.id.search_Iv);
        selector = (ImageView) this.findViewById(R.id.ii_category_selector);
        tab_ly = (LinearLayout) this.findViewById(R.id.tab_ly);
        ViewTreeObserver vto = tab_ly.getViewTreeObserver();//用来获取中间tab的宽度
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                if (hasMeasured == false) {
                    height = tab_ly.getMeasuredHeight();
                    width = tab_ly.getMeasuredWidth();
                    //获取到宽度和高度后,可用于计算
                    hd.sendEmptyMessage(0);
                    hasMeasured = true;
                }
                return true;
            }
        });
        home = (TextView) this.findViewById(R.id.home);
        home.setSelected(true);
        card = (TextView) this.findViewById(R.id.club_card);
        my = (TextView) this.findViewById(R.id.my);
        viewPager = (ViewPager) findViewById(R.id.main_vp);
        viewPager.setCurrentItem(0);


    }

    /**
     * 初始化下划线位置
     */
    private void initSelector() {//获取图片的宽度,和整个tab的宽度,(单个tab的宽度-图片的宽度)/2得到了向右边偏移多少才能到第一个tab的中心
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.menu_line);//获取下划线图片
        int bitmapWidth = bitmap.getWidth();
        float left = (width/ 3 - bitmapWidth) / 2;
        Matrix matrix = new Matrix();
        matrix.postTranslate(left, 0);
        selector.setImageMatrix(matrix);
    }

    @Override
    protected void setListener() {
        search_Iv.setOnClickListener(this);
        select_city_Rlty.setOnClickListener(this);
        home.setOnClickListener(this);
        card.setOnClickListener(this);
        my.setOnClickListener(this);
        viewPager.setOnPageChangeListener(onPageChangeListener);
    }


   

    @Override
    protected void init() {
        PushAgent.getInstance(this).onAppStart();
//        PushAgent.getInstance(this).enable(mRegisterCallback);
        PushAgent.getInstance(this).enable();
        PushAgent.getInstance(this).setPushIntentServiceClass(UmengIntentService.class);
        String device_token = UmengRegistrar.getRegistrationId(MainActivity.this);
        LogUtils.i(TAG, "device_token:" + device_token);


        if (mDldDBHelper == null) {
            mDldDBHelper = DldDBHelper.getDldDBHelper(this);
        }
        try {
            movieCityDao = mDldDBHelper.getMovieCityDao();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        requestCityList();    //请求电影票模块城市列表
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.setPriority(Integer.MAX_VALUE);// 设置优先级为最高.

        MobclickAgent.setDebugMode(false);
        // SDK在统计Fragment时,需要关闭Activity自带的页面统计,
        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.updateOnlineConfig(this);
        initPager();


        // 监听home键广播
        mHomeKeyEventBroadCastReceiver = new HomeKeyEventBroadCastReceiver();
        registerReceiver(mHomeKeyEventBroadCastReceiver, new IntentFilter(
                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
        // 屏幕开启关闭
        mScreenBroadCastReceiver = new ScreenBroadCastReceiver();
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mScreenBroadCastReceiver, filter);
        SelectCityActivity.registObserver(mNotifyChangeObserver);//选择城市的监听
        processSelectCityName();
    }

    /**
     * viewpager添加数据
     */
    private void initPager() {
        pagers = new ArrayList<Fragment>();
        // 首页
        HomeFragment HomeFragment = new HomeFragment();
        pagers.add(HomeFragment);
        // 会员卡
        AttractionsMiserCardFragment AttractionsMiserCardFragment = new AttractionsMiserCardFragment();
        pagers.add(AttractionsMiserCardFragment);
        // 我的
        PersonalCenterInfoFragment PersonalCenterInfoFragment = new PersonalCenterInfoFragment();
        pagers.add(PersonalCenterInfoFragment);
        pagerAdapter = new BusinessRankAdapter(getSupportFragmentManager(), pagers);
        viewPager.setAdapter(pagerAdapter);
        requestAppVersion();
    }

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

        @Override
        public void onPageSelected(int position) {
            home.setSelected(false);
            card.setSelected(false);
            my.setSelected(false);
            switch (position) {
                case 0:
                    home.setSelected(true);
                    break;
                case 1:
                    card.setSelected(true);
                    break;
                case 2:
                    my.setSelected(true);
                    break;
            }
            //下划线移动
            TranslateAnimation animation = new TranslateAnimation(curentlay * width / 3, position * width / 3, 0, 0);
            animation.setFillAfter(true);
            animation.setDuration(200);
            selector.startAnimation(animation);
            curentlay = 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.home:
                viewPager.setCurrentItem(0);
                break;
            case R.id.club_card:
                viewPager.setCurrentItem(1);
                break;
            case R.id.my:
                viewPager.setCurrentItem(3);
                break;
            case R.id.select_city_Rlty://选择城市
                Intent intent = new Intent(this, SelectCityActivity.class);
                intent.putExtra("flag", "HomeFragment");
                startActivity(intent);
                break;
            case R.id.search_Iv://搜索
                Intent intentx = new Intent(this, SearchActivity.class);
                startActivity(intentx);
                break;
        }
    }

    /**
     * @Description:[刷新选择的城市]
     */
    public void processSelectCityName() {
        String cityName = PreferencesUtils.getString(this,
                AppConfig.CITY_NAME);
        if (!StringUtils.isBlank(cityName)) {
            select_city_Tv.setText(cityName);
        }
    }

    SelectCityActivity.NotifyChangeObserver mNotifyChangeObserver = new SelectCityActivity.NotifyChangeObserver() {

        @Override
        public void onChangeCity(String cityId, String cityName) {
            LogUtils.e(TAG, "cityId:" + cityId + "    cityName:" + cityName);
            processSelectCityName();
        }
    };


    public Handler handler = new Handler();
    public IUmengRegisterCallback mRegisterCallback = new IUmengRegisterCallback() {

        @Override
        public void onRegistered(String registrationId) {
            // TODO Auto-generated method stub
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    updateStatus();
                }
            });
        }
    };

    private void updateStatus() {
        String pkgName = getApplicationContext().getPackageName();
        String info = String.format("enabled:%s  isRegistered:%s  DeviceToken:%s",
                PushAgent.getInstance(this).isEnabled(), PushAgent.getInstance(this).isRegistered(),
                PushAgent.getInstance(this).getRegistrationId());

        LogUtils.i(TAG, "应用包名:" + pkgName + "\n" + info + "updateStatus:" + String.format("enabled:%s  isRegistered:%s",
                PushAgent.getInstance(this).isEnabled(), PushAgent.getInstance(this).isRegistered()));
        LogUtils.i(TAG, "=============================");
    }

    ;



 
    @Override
    protected void onResume() {
        super.onResume();
        LocationUtil.getInstance().start();
        LogUtils.d(TAG, "定位开启...............................");
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if (mArcMenu.isShown()) {
//                mArcMenu.fold();
//                return true;
//            }
            if (curentlay == 0) {// 首页时候才会触发退出事件
                appExit();
            } else {
                curentlay = 0;
//                currentTabByTag(curentlay);
                viewPager.setCurrentItem(curentlay);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

  
    /**
     * @description 请求网络检查版本是否有新版本
     */
    private void requestAppVersion() {
        EncryptGetRequest req = new EncryptGetRequest(Urls.CHECK_VERSION_URL,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null) {
                            CheckVersionResBean mCheckVersionResBean = CheckVersionResBean
                                    .parse(response);
                            LogUtils.i(TAG, mCheckVersionResBean.toString());
                            processCheckVersion(mCheckVersionResBean);
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtils.e(TAG, "VolleyError: " + error);
            }
        });
        BaseApplication.getInstance().addToRequestQueue(req);
        LogUtils.i(TAG, req.getUrl());

    }

    /**
     * @Description:[检查版本更新]
     */
    private void processCheckVersion(CheckVersionResBean mCheckVersionResBean) {
        // 对比当前软件的version和网站的version
        int now_version = AppInfoUtil.getVersionCode(MainActivity.this);
        String version = mCheckVersionResBean.getVersion();
        if (!StringUtils.isBlank(version)) {
            int net_version = Integer.parseInt(version);
            LogUtils.i(TAG, "net_version==" + net_version + " now_version="
                    + now_version);
            if (now_version < net_version) {// 有新版本,需要升级
                PreferencesUtils.putBoolean(getApplicationContext(),
                        "isVersionUpdates", true);

//                new_version_caution_Iv.setVisibility(View.VISIBLE);
                // 出现提示对话框
                initAlertDialog(mCheckVersionResBean);
            } else {

//                new_version_caution_Iv.setVisibility(View.GONE);
                PreferencesUtils.putBoolean(getApplicationContext(),
                        "isVersionUpdates", false);
            }
        }

    }

    /**
     * @param mCheckVersionResBean
     * @Description:[弹出版本更新的提示]
     */
    private void initAlertDialog(final CheckVersionResBean mCheckVersionResBean) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("版本更新提示")
                .setMessage(mCheckVersionResBean.getNote())
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.putExtra("url", mCheckVersionResBean.getUrl());
                        intent.setClass(MainActivity.this, UpdateService.class);
                        MainActivity.this.startService(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create();
        dialog.show();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    // 退出程序
    private void appExit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showShortToast("再按一次返回键退出程序");
            exitTime = System.currentTimeMillis();

        } else {
            PreferencesUtils.putInt(getApplicationContext(), "setCurrendIndex",
                    0);
            AppManager.getAppManager().AppExit(getApplicationContext());
            finish();
            System.exit(0);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        ((BitmapDrawable) blurView.getDrawable()).getBitmap().recycle();
        unregisterReceiver(mHomeKeyEventBroadCastReceiver);
        unregisterReceiver(mScreenBroadCastReceiver);
        LocationUtil.getInstance().stop();
    }

    /**
     * HOME键
     */
    class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
        static final String SYSTEM_REASON = "reason";
        static final String SYSTEM_HOME_KEY = "homekey";// home key
        static final String SYSTEM_RECENT_APPS = "recentapps";// long home key

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (reason != null) {
                    if (reason.equals(SYSTEM_HOME_KEY)) {
                        LogUtils.d(TAG, "定位关闭.............................");
                        LocationUtil.getInstance().stop();
                        LogUtils.d(TAG, "HOME键...");
                    }
                }
            }
        }
    }

    /**
     * 屏幕关闭
     */
    class ScreenBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                LogUtils.d(TAG, "屏幕开启...");
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                LogUtils.d(TAG, "定位关闭.............................");
                LocationUtil.getInstance().stop();
                LogUtils.d(TAG, "屏幕关闭...");

            }
        }
    }

    /**
     * 检查登录状态
     *
     * @param userInfos 用户bean
     * @return true:已登录/false:未登录
     */
    private boolean checkLoginState(User userInfos) {
        if (userInfos == null
                || (userInfos != null && StringUtils
                .isBlank(userInfos.username))) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 从登录界面跳转过来,开始验证是否激活了voip
//        if (requestCode == Constant.LOGIN_FOR_VOIP_REQUEST_CODE
//                && resultCode == RESULT_OK) {
//            new Handler().postDelayed(new Runnable() {
//
//                @Override
//                public void run() {
//                    mArcMenu.getOnItemClickListener().onItemClick(0);
//                }
//            }, 500);
//        }
    }


    /**
     * @Description:[请求城市列表]
     */
    public void requestCityList() {

        EncryptGetRequest req = new EncryptGetRequest(Urls.MOVIE_CITY_LIST_URL, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                dismissProgressDialog();
                if (response != null) {
                    MovieCityBean movieCityBean = MovieCityBean.parse(response);
                    if (movieCityBean != null) {

                        filledData(movieCityBean);

                    }
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtils.e(TAG, "VolleyError: " + error);

            }
        });

        BaseApplication.getInstance().addToRequestQueue(req, this);
        LogUtils.i(TAG, "req.getUrl(): " + req.getUrl());
    }

    private void filledData(MovieCityBean movieCityBean) {
        MovieCityBean cityBean = null;
        LinkedHashMap<String, HashMap<String, String>> citiesMap = movieCityBean.cities;
        if (citiesMap != null) {
            try {
                mDldDBHelper.cleanMovieCityDataTable();   //清空表中原有数据
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 添加城市
            for (Iterator iterator = citiesMap.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry<String, HashMap<String, String>> entry = (Map.Entry<String, HashMap<String, String>>) iterator.next();
                // 添加城市ID 名字
                for (Iterator iterator2 = entry.getValue().entrySet().iterator(); iterator2.hasNext(); ) {
                    Map.Entry<String, String> entry2 = (Map.Entry<String, String>) iterator2.next();
                    cityBean = new MovieCityBean();

                    cityBean.setCityName(entry2.getValue());
                    cityBean.setCitykey(entry2.getKey());
                    if (StringUtils.isBlank(entry.getKey())) {
                        cityBean.setSortLetters("#");
                    } else {
                        cityBean.setSortLetters(entry.getKey());
                    }
                    try {
                        insertData(cityBean);
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }


        }

    }

    private void insertData(MovieCityBean cityBean) throws SQLException {
        MovieCityData mMovieCityData = new MovieCityData();
        mMovieCityData.setCityName(cityBean.getCityName());
        mMovieCityData.setCityCode(cityBean.getCitykey());
        mMovieCityData.setSortLetters(cityBean.getSortLetters());
        mMovieCityData.setType(AppConfig.CITY_NORMAL);
        movieCityDao.create(mMovieCityData);

    }


    /**
     * @Description:[显示分享弹框]
     */
    private void showShareDialog(String userId) {
        if (mRecommendDialog == null) {
            mRecommendDialog = new RecommendDialog(this, R.style.ShareDialog);
        }
        if (!mRecommendDialog.isShowing()) {
            mRecommendDialog.showRequestDialog(userId, "这个软件可以查到很全的打折促销哦!", "");
        }
    }

}

这个是其中一个fragment的代码

public class AttractionsMiserCardFragment extends BaseFragment {

    private String TAG = AttractionsMiserCardActivity.class.getSimpleName();
    private Activity mActivity;
    private View layoutView;
    private ListView card_list;
    private CardListAdapter cardlistadapter;
    private String[] name = new String[]{"会员卡简介", "办卡须知", "在线激活", "会员卡使用说明", "购卡电话:"};
    private String[] url = new String[]{"http://m.dld.com/index.php?act=cheapskate&op=instruction", "http://m.dld.com/index.php?act=cheapskate&op=characteristic", "http://card.dldpay.com/carderWeb/activateOnlineMobile.jsp", "http://m.dld.com/index.php?act=cheapskate&op=instructions","tel:400-0088-114"};


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (layoutView == null) {
            layoutView = inflater.inflate(R.layout.activity_attractions_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 onResume() {
        super.onResume();
        MobclickAgent.onResume(mActivity);
        MobclickAgent.onPageStart(TAG);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(mActivity);
        MobclickAgent.onPageEnd(TAG);
    }

    @Override
    protected void findViewById() {
        card_list = (ListView) layoutView.findViewById(R.id.card_list);
    }

    @Override
    protected void setListener() {
        card_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position!=4){
                    Intent intent = new Intent(mActivity, AttractionsMiserCardActivity.class);
                    intent.putExtra("url",url[position]);
                    if (position!=2) {
                        intent.putExtra("card", true);
                    }
                    mActivity.startActivity(intent);
                }else {
                    Intent intent2 = new Intent();
                    //系统默认的action,用来打开默认的电话界面
                    intent2.setAction(Intent.ACTION_DIAL);
                    intent2.setData(Uri.parse(url[position]));
                    mActivity.startActivity(intent2);
                }
            }
        });
    }

    @Override
    protected void init() {
        cardlistadapter = new CardListAdapter(mActivity, name);
        card_list.setAdapter(cardlistadapter);
    }

    private class CardListAdapter extends BaseAdapter {
        private String[] list;
        private Context mContext;

        public CardListAdapter(Context context, String[] list) {
            this.list = list;
            this.mContext = context;
        }

        @Override
        public int getCount() {
            return this.list.length;
        }

        @Override
        public Object getItem(int position) {
            return list[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_card_fragment, null);
                viewHolder.log = (ImageView) convertView.findViewById(R.id.logo_Iv);
                viewHolder.name_Tv = (TextView) convertView.findViewById(R.id.name_tv);
                viewHolder.tel_Tv = (TextView) convertView.findViewById(R.id.tel_Tv);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.tel_Tv.setVisibility(View.GONE);
            String name = list[position];
            if (!StringUtils.isBlank(name)) {
                if (position == 4) {
                    viewHolder.tel_Tv.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.name_Tv.setText(name);
                }
                switch (position) {
                    case 0:
                        viewHolder.log.setImageResource(R.drawable.icon_car_1);
                        break;
                    case 1:
                        viewHolder.log.setImageResource(R.drawable.icon_car_2);
                        break;
                    case 2:
                        viewHolder.log.setImageResource(R.drawable.icon_car_3);
                        break;
                    case 3:
                        viewHolder.log.setImageResource(R.drawable.icon_car_4);
                        break;
                    case 4:
                        viewHolder.log.setImageResource(R.drawable.icon_car_5);
                        break;
                }
            }
            return convertView;
        }

        public class ViewHolder {
            ImageView log;
            TextView name_Tv;
            TextView tel_Tv;
        }
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = getActivity();
        //Log.d(TAG, "onAttach");
    }
}
最后是我们的viewpagers的adapter

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);
    }



}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值