首页 > 代码库 > 360手机助手(二):侧拉栏drawerLayout+Tab+Viewpager+ListView+Pulltorefresh+imageloder

360手机助手(二):侧拉栏drawerLayout+Tab+Viewpager+ListView+Pulltorefresh+imageloder

整个项目的框架在ContentPager,要熟悉这个类。

简介

完成侧拉栏的显示,侧拉首页对应的:首页+应用+游戏这3个 tab,包含的知识点有:请求数据 +pullTofresh + ImageLoader +轮播图 + listView

效果图:
技术分享

侧拉栏的实现

V4包中的DrawerLayout实现侧拉效果,每个侧拉的item对应一个fragment,点击该item时,先把所有的fragment隐藏 + 文字设置未选中,然后才创建对应的fragment并显示

技术分享

怎么实现侧拉栏的显示与隐藏?

点击ActionBar的导航图标实现侧拉栏的显示与隐藏。先要获取ActionBar和DrawerLayout,再创建ActionBarDrawerToggle并设置导航图标,最后给drawerlayout添加侧栏监听及toggle,当然要想侧栏栏出现,还要在onOptionsItemSelected()方法中加这一行代码:toggle.onOptionsItemSelected(item);

private void initDrawerLayout() {
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    // 创建监听对(ActionBarDrawerToggle 实现了DrawerLayout.DrawerListener),添加导航图标
    toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer_am, 0, 0);
    toggle.syncState();// 少了这一行,ic_drawer_am就是默认的图标,不是我们指定的。
    drawerLayout.setDrawerListener(toggle);
}

/**
 * 要想侧栏栏出现,还要加这一行代码:toggle.onOptionsItemSelected(item);
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    toggle.onOptionsItemSelected(item);
    return super.onOptionsItemSelected(item);
}

ActionBar的设置

技术分享

private void initActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setIcon(R.drawable.ic_launcher);// 设置home图标
    actionBar.setDisplayShowHomeEnabled(true);// 显示home图标
    actionBar.setHomeButtonEnabled(true);// home图标可点击
    actionBar.setDisplayHomeAsUpEnabled(true);// 显示导航图标
}

侧栏按的item点击

@Override
public void onClick(View v) {
    setAllFalse();
    transaction = fm.beginTransaction();
    hideAllFragment();// 先创建FragmentTransaction对象,在隐藏
    switch (v.getId()) {
    case R.id.home_layout:
        tv_home.setSelected(true);
        if (homeFrag == null) {
            homeFrag = new HomeFragment();
            transaction.add(R.id.frame_home, homeFrag, "HomeFragment");
        }
        transaction.show(homeFrag);
        break;
    case R.id.setting_layout:
        tv_setting.setSelected(true);
        if (setFrag == null) {
            setFrag = new SettingFragment();
            transaction.add(R.id.frame_home, setFrag, "SettingFragment");
        }
        transaction.show(setFrag);
        break;
        }
    drawerLayout.closeDrawers();
    transaction.commit();
}

HomeFrag:listView显示数据

先用listview显示数据,在添加pullTofresh+ imageloader,然后添加轮播图
注意:更新ui需要再主线程,所以CommonUtil.runOnUIThread(…)

HomeFrag

技术分享

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    contentPager = new ContentPager(getActivity()) {

        @Override
        public Object requestData() {
            return getData();
        }

        @Override
        public View createSuccessView() {
            return getSuccessView();
        }
    };
    return contentPager;
}

protected View getSuccessView() {
    view = View.inflate(getActivity(), R.layout.frag_home, null);
    listView = (ListView) view.findViewById(R.id.listView);
    adapter = new HomeFragAdapter(appsList);
    listView.setAdapter(adapter);
    return view;
}

protected Object getData() {
    String json = HttpHelper.get(NetUrl.GAME +appsList.size());
    List<AppInfoBean> list = (List<AppInfoBean>) GsonUtil.jsonToList(json, new TypeToken<List<AppInfoBean>>() {}.getType());
    addAndRefreshData(list);
    return list;
}

private void addAndRefreshData(List<AppInfoBean> list) {
    appsList.addAll(list);

    CommonUtil.runOnUIThread(new Runnable() {

        @Override
        public void run() {
            adapter.notifyDataSetChanged();
        }
    });
}

HomeFragAdapter:

格式化app的大小:包:String android.text.format: 方法: Formatter.formatFileSize(Context context, long number)

public class HomeFragAdapter extends MyBaseAdapter<AppInfoBean> {

    public HomeFragAdapter(List<AppInfoBean> list) {
        super(list);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.item_home_frag, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        AppInfoBean info = list.get(position);

        ImageLoader.getInstance().displayImage(NetUrl.IMAGE_PREFIX + info.getIconUrl(), holder.iv, ImageLoaderOptions.options);
        holder.tv_name.setText(info.getName());
        holder.tv_size.setText("" + Formatter.formatFileSize(MyApplication.getContext(), info.getSize()));
        holder.tv_desc.setText(info.getDes());
        holder.ratingBar.setRating(info.getStars());

        return convertView;
    }

    public class ViewHolder {

        public ImageView iv;
        public RatingBar ratingBar;
        public TextView tv_name;
        public TextView tv_size;
        public TextView tv_desc;

        public ViewHolder(View itemView) {
            super();
            iv = (ImageView) itemView.findViewById(R.id.iv_item_frag_home);
            ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
            tv_name = (TextView) itemView.findViewById(R.id.tv_name_frag_home);
            tv_size = (TextView) itemView.findViewById(R.id.tv_app_size_frag_home);
            tv_desc = (TextView) itemView.findViewById(R.id.tv_app_desc_frag_home);
        }
    }
}

添加刷新 pulltorefresh

参考:第三方开源库:Android-PullToRefresh-master简单使用

protected View getSuccessView() {
    view = View.inflate(getActivity(), R.layout.frag_home, null);
    ptr = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
    ptr.setMode(Mode.BOTH);
    ptr.setOnRefreshListener(new OnRefreshListener<ListView>() {

        @Override
        public void onRefresh(PullToRefreshBase<ListView> refreshView) {
            if (refreshView.getCurrentMode() == Mode.PULL_FROM_START) {// 下拉刷新
                handler.sendEmptyMessageDelayed(WHAT1, 1500);
            } else {// 上拉加载更多
                // handler.sendEmptyMessageDelayed(WHAT2, 1500);//模拟上拉加载更多
                contentPager.loadDataAndRefresh();
            }
        }

    });
    listView = ptr.getRefreshableView();
    adapter = new HomeFragAdapter(appsList);
    listView.setAdapter(adapter);
    return view;
}

imageloader

第三方开源库:imageLoader的使用

先要在application中初始化,在设置DisplayImageOptions,然后根据url显示图片

ImageLoader.getInstance().displayImage(NetUrl.IMAGE_PREFIX + info.getIconUrl(), holder.iv, ImageLoaderOptions.options);

轮播图

private void initBanner() {
    findHeadViews();
    initPictDescList();
    initDots();

    initViewPager();
}

private void initViewPager() {
    BannerPagerAdapter adapter = new BannerPagerAdapter(pictUrlList);
    viewPager.setAdapter(adapter);
    listView.addHeaderView(headView);
    tv_desc.setText("第一张图");
    tv_ratio.setText(1 + "/" + pictUrlList.size());
    viewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            tv_desc.setText(pictDescList.get(position));
            tv_ratio.setText(1 + position + "/" + pictUrlList.size());
            for (int i = 0; i < dotsList.size(); i++) {
                if (i == position) {
                    dotsList.get(i).setBackgroundResource(R.drawable.dot_focus);
                } else {
                    dotsList.get(i).setBackgroundResource(R.drawable.dot_normal);
                }
            }
        }

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

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    });
}

private void findHeadViews() {
    headView = View.inflate(MyApplication.getContext(), R.layout.layout_banner, null);
    viewPager = (ViewPager) headView.findViewById(R.id.viewpager_banner);
    tv_desc = (TextView) headView.findViewById(R.id.tv_desc_banner);
    tv_ratio = (TextView) headView.findViewById(R.id.tv_ratio_banner);
    ll_dots = (LinearLayout) headView.findViewById(R.id.ll_dots);
}

private void initDots() {
    ll_dots.removeAllViews();
    dotsList.clear();

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);
    for (int i = 0; i < pictUrlList.size(); i++) {
        TextView tv = new TextView(getActivity());
        if (i == 0) {
            tv.setBackgroundResource(R.drawable.dot_focus);
        } else {
            tv.setBackgroundResource(R.drawable.dot_normal);
        }
        params.setMargins(10, 0, 0, 0);
        ll_dots.addView(tv, params);
        dotsList.add(tv);
    }
}

private void initPictDescList() {
    for (int i = 0; i < pictUrlList.size(); i++) {
        pictDescList.add("第" + (i + 1) + "张图");
    }
}

RatingBar

技术分享

<RatingBar
    android:id="@+id/ratingBar"
    style="@android:style/Widget.RatingBar"
    android:layout_width="wrap_content"
    android:layout_height="14dp"
    android:layout_marginBottom="2dp"
    android:layout_marginTop="2dp"
    android:isIndicator="true"
    android:progressDrawable="@drawable/ratingbar_drawable" />

ratingbar_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background" android:drawable="@drawable/rating_small_empty" />
    <item android:id="@+android:id/secondaryProgress" android:drawable="@drawable/rating_small_half" />
    <item android:id="@+android:id/progress" android:drawable="@drawable/rating_small_full" />
</layer-list>

源码

https://git.oschina.net/googlepalycqc/GooglePlayCQCDay02

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    360手机助手(二):侧拉栏drawerLayout+Tab+Viewpager+ListView+Pulltorefresh+imageloder