編輯:關於 Android 程式設計
GridView 默认是垂直滚动的,但很多应用场景需要实现多行、水平滚动的分页效果,比如首页的运营位轮播。本文将带大家一起实现一个这样的自定义分页 GridView。
(1)比如每页显示 2×2,总共 2×N,每个 item 显示图片加文字(点击可跳转)。如果单行水平滚动,可以用 HorizontalScrollView 实现;如果是多行水平滚动,则需要结合 GridView(一般垂直滚动)和 HorizontalScrollView 来实现。
(2)水平滚动翻页,下方有显示当前页的 icon 指示器。
因为翻页时需要把当前页传给调用者,所以 fling 函数中自己实现而不要调用父类的 fling:
public class DrawerHScrollView extends HorizontalScrollView {
private static final String TAG = "DrawerHScrollView";
private IDrawerPresenter drawerPresenter = null;
private int currentPage = 0;
private int totalPages = 1;
private static Hashtable<Integer, Integer> positionLeftTopOfPages = new Hashtable();
public DrawerHScrollView(Context context) { super(context); }
public DrawerHScrollView(Context context, AttributeSet attrs) { super(context, attrs); }
public DrawerHScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
public void cleanup() {
currentPage = 0;
totalPages = 1;
drawerPresenter = null;
if (positionLeftTopOfPages != null) { positionLeftTopOfPages.clear(); }
}
public void setParameters(int totalPages, int currentPage, int scrollDisX) {
this.totalPages = totalPages;
this.currentPage = currentPage;
positionLeftTopOfPages.clear();
for (int i = 0; i < totalPages; i++) {
int posx = (scrollDisX) * i;
positionLeftTopOfPages.put(i, posx);
}
smoothScrollTo(0, 0);
}
public void setPresenter(IDrawerPresenter drawerPresenter) {
this.drawerPresenter = drawerPresenter;
}
@Override
public void fling(int velocityX) {
boolean change_flag = false;
if (velocityX > 0 && (currentPage < totalPages - 1)) {
currentPage++;
change_flag = true;
} else if (velocityX < 0 && (currentPage > 0)) {
currentPage--;
change_flag = true;
}
if (change_flag) {
int postionTo = (Integer) positionLeftTopOfPages.get(new Integer(currentPage)).intValue();
smoothScrollTo(postionTo, 0);
drawerPresenter.dispatchEvent(totalPages, currentPage);
}
// super.fling(velocityX);
}
}
<com.example.multilinegridview.DrawerHScrollView
android:id="@+id/hscrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:scrollbars="none"
android:layout_below="@id/layout_drawer_top"
android:layout_above="@id/layout_pagenumber"
android:background="#CCCCCC" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<GridView
android:id="@+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</com.example.multilinegridview.DrawerHScrollView>
public interface IDrawerPresenter {
IDrawerPresenter getInstance();
void dispatchEvent(int totalPages, int currentPage);
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/layout_item"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:background="#FFFFFF">
<ImageView
android:id="@+id/ivIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="优惠券1"
android:textColor="#000000" />
</LinearLayout>
(1)实现 IDrawerPresenter 接口,在 HorizontalScrollView 里通过该接口返回当前页,从而更新 page indicator:
@Override
public IDrawerPresenter getInstance() { return this; }
@Override
public void dispatchEvent(int totalPages, int currentPage) {
Message msg = Message.obtain();
msg.what = MSG_DRAWER_UPDATE_PAGE_LAYOUT;
msg.arg1 = totalPages;
msg.arg2 = currentPage;
handler.sendMessage(msg);
}
(2)PageItemImageView 和 page indicator 的更新。PageItemImageView 显示 normal 状态的指示器,之后再把当前页的图标换成 selected:
protected class PageItemImageView extends ImageView {
public PageItemImageView(Context context) {
super(context);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_page_normal);
this.setImageBitmap(bitmap);
}
}
public void updateDrawerPageLayout(int total_pages, int sel_page) {
layout_pagenumber.removeAllViews();
if (total_pages <= 0 || sel_page < 0 || sel_page >= total_pages) { return; }
for (int i = 0; i < total_pages; i++) {
if (i != 0) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(5, 0, 0, 0);
layout_pagenumber.addView(new PageItemImageView(this), params);
} else {
layout_pagenumber.addView(new PageItemImageView(this));
}
}
PageItemImageView selItem = (PageItemImageView) layout_pagenumber.getChildAt(sel_page);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_page_selected);
selItem.setImageBitmap(bitmap);
}
(3)DrawerListAdapter 适配器:
private class DrawerListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private LinearLayout layout_item;
private TextView tvTitle;
private ImageView ivIcon;
private final Context context;
private int colWid;
private int colHei;
public DrawerListAdapter(Context context, int colWid, int colHei) {
this.context = context;
this.colWid = colWid;
this.colHei = colHei;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() { return drawerItemList.size(); }
public Object getItem(int position) { return drawerItemList.get(position); }
public long getItemId(int position) { return position; }
public View getView(int position, View convertView, ViewGroup parent) {
DrawerItem item = drawerItemList.get(position);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drawer_item, null);
layout_item = (LinearLayout) convertView.findViewById(R.id.layout_item);
ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
if (colHei != 0 && colWid != 0) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(colWid, colHei - 30);
ivIcon.setLayoutParams(params);
}
convertView.setTag(layout_item);
} else {
layout_item = (LinearLayout) convertView.getTag();
}
ivIcon.setImageResource(R.drawable.ic_launcher);
tvTitle.setText(String.valueOf(position));
return convertView;
}
}
(4)DrawerItemClickListener 实现 OnItemClickListener。
(5)updateDrawerLayout。获得 data 的 size 后可以算出列数得到固定行数,再算出 GridView 的宽度。因为每页显示 2 列,最后一页可能右侧为空,为了让翻页更顺滑,可以给 GridView 增加一列空白。
int numCols = (drawerItemList.size() - 1) / 2 + 1
int gridViewWid = numCols * colWid + (numCols + 1) * spaceing;
if (numCols % 2 == 1) {
gridViewWid += colWid + spaceing;
}
public void updateDrawerLayout() {
if ((drawerItemList == null) || (drawerItemList.size() == 0)) { return; }
if (!hasMeasured) { return; }
int scrollWid = hscrollview.getWidth();
int scrollHei = hscrollview.getHeight();
if (scrollWid <= 0 || scrollHei <= 0) { return; }
int spaceing = 10;
int colWid = (scrollWid - spaceing * 3) / 2;
int colHei = (scrollHei - spaceing * 3) / 2;
int numCols = (drawerItemList.size() - 1) / 2 + 1;
int gridViewWid = numCols * colWid + (numCols + 1) * spaceing;
// 如果 numCols 是奇数(比如 5),补充空白列
if (numCols % 2 == 1) { gridViewWid += colWid + spaceing; }
LayoutParams params = new LayoutParams(gridViewWid, scrollHei);
gridView.setLayoutParams(params);
gridView.setColumnWidth(colWid);
gridView.setHorizontalSpacing(spaceing);
gridView.setVerticalSpacing(spaceing);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setNumColumns(numCols);
adapter = new DrawerListAdapter(this, colWid, colHei);
listener = new DrawerItemClickListener();
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(listener);
int pageNum = (drawerItemList.size() - 1) / 4 + 1;
hscrollview.setParameters(pageNum, 0, scrollWid - spaceing);
updateDrawerPageLayout(pageNum, 0);
}
效果图:
實作 Android ListView 項目滑動刪除效果
本文示範如何為 ListView 的每一個項目加上「滑動顯示刪除按鈕」的互動效果,透過自訂的 Adapter 攔截觸控事件,判斷使用者是水平滑動還是單純點擊。 首先是 M
Android RecyclerView 全面解析:告別 ListView 的插拔式列表神器
RecyclerView 問世已經有一段時間,大家可以通過引入 support-v7 庫來使用它。官方對它的定位是:在有限窗口內展示大量數據集。聽到這個描述,你應該會聯想
Android ClassLoader 熱修復技術流派縱覽
大約在 2015 年 10 月底,QQ 空間發表了一篇名為《安卓 App 熱補丁動態修復技術介紹》的文章。文中提到,要讓 Class 能夠進行熱修復,其中一個關鍵條件就是
Android 無限自動滾動 ViewPager 實作
首頁常見的輪播圖,通常需要自動播放且可無限循環。若直接讓使用者從第一張往左滑,容易出現空白,因此需要特別處理。 無限滑動原理 將 PagerAdapter 的 getC