編輯:關於Android編程
最近實在太忙,一個多禮拜沒有更新文章了,於是今晚加班加點把demo寫出來,現在都12點了才開始寫文章。
把RecyclerView下拉刷新上拉加載更多加入到我們的開發者頭條APP中。
我們找開源項目肯定首選github,去搜索一下一大堆,如果效果圖是你想要的功能的話,然後找排名靠前,收藏比較多的項目吧,我找的項目是CommonPullToRefresh,支持ListView,RecyclerView,GridView,SwipeRefreshLayout等常用控件。我跑了一下Demo,沒啥bug,挺好用的。
1).module導入進來,然後主項目依賴一下,這裡有不會的看我另外一篇文章Android Studio 入門,裡面有講到Android Studio添加項目依賴。
2).代碼實現,我們這邊就是修改SelectedFragment
首先我們看布局文件的變化,在RecyclerView外面包裹了自定義的一個類PtrClassicFrameLayout,內部實現了下拉刷新,上拉加載更多。還可以設置自定義屬性,都是啥意思我就不解釋了。
再來看onCreateView方法,這個代碼就不解釋了。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_selected, null);
ptrClassicFrameLayout = (PtrClassicFrameLayout) rootView.findViewById(R.id.test_recycler_view_frame);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.test_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
init();
return rootView;
}
在onCreateView裡面調用了init()方法,我們來瞧瞧怎麼實現的。這裡解釋一下為什麼要對適配器進行包裝,這樣的目的在包裝類裡面處加入頭部,底部View,處理點擊事件。大家拿到源碼了之後自己也可以看看。
private void init() {
//初始化適配器
selectedAdapter = new SelectedRecyclerAdapter(getActivity());
//對適配器進行封裝
mAdapter = new RecyclerAdapterWithHF(selectedAdapter);
//把滾動Banner加入頭部
mAdapter.addCarouse(initCarouselHead());
mRecyclerView.setAdapter(mAdapter);
ptrClassicFrameLayout.setPtrHandler(ptrDefaultHandler);//設置下拉監聽
ptrClassicFrameLayout.setOnLoadMoreListener(onLoadMoreListener);//設置上拉監聽
ptrClassicFrameLayout.setLoadMoreEnable(true);//設置可以加載更多
}
mAdapter.addCarouse(initCarouselHead()); 初始化一個滾動Banner,然後加入適配器頭部。這個我前面的教程應該已經講過了。。
//初始化
private View initCarouselHead(){
View headView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_selected_header,mRecyclerView,false);
tvContent=(TextView) headView.findViewById(R.id.tv_content);
tvContent.setText(carousePageStr[0]);
viewPager = (ViewPager)headView.findViewById(R.id.viewpager);
selectedPagerAdapter=new SelectedPagerAdapter(getActivity(),carousePagerSelectView);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.addOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(selectedPagerAdapter);
ViewGroup group = (ViewGroup) headView.findViewById(R.id.viewGroup);// 初始化底部顯示控件
tips = new ImageView[3];
for (int i = 0; i < tips.length; i++){
ImageView imageView = new ImageView(getActivity());
if (i == 0) {
imageView.setBackgroundResource(R.mipmap.page_indicator_focused);
} else {
imageView.setBackgroundResource(R.mipmap.page_indicator_unfocused);
}
tips[i] = imageView;
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
layoutParams.leftMargin = 10;// 設置點點點view的左邊距
layoutParams.rightMargin = 10;// 設置點點點view的右邊距
group.addView(imageView, layoutParams);
}
timer = new Timer(true);//初始化計時器
timer.schedule(task, 0, CAROUSEL_TIME);//延時0ms後執行,3000ms執行一次
return headView;
}
SelectedRecyclerAdapter 必須繼承RecyclerView.Adapter
這玩意跟ListView的適配器差不多,用過ListView適配器的應該一看就懂了。
首先會調用getItemCount,知道我要顯示多少item。
知道了行數然後就是循環調用onCreateViewHolder跟onBindViewHolder了,onCreateViewHolder就是創建一個item的View,onBindViewHolder就會把上次創建的item的View傳入進來,還有一個下標,這樣我們就能給每一行賦值,這兩個方法都是先後一起調用。item回收重用的機制應該跟ListView一樣的。
public class SelectedRecyclerAdapter extends RecyclerView.Adapter {
private List selectedArticles;
private LayoutInflater inflater;
public SelectedRecyclerAdapter(Context context) {
super();
inflater = LayoutInflater.from(context);
selectedArticles = new ArrayList();
initData();
}
private void initData() {
for (int i = 0; i < 10; i++) {
SelectedArticle selectedArticle = new SelectedArticle(i, "Android開發666", i, i, "");
selectedArticles.add(selectedArticle);
}
}
public void loadMore(int page) {
for (int i = 0; i < 5; i++) {
SelectedArticle selectedArticle = new SelectedArticle(i, "第" + page + "頁數據", i, i, "");
selectedArticles.add(selectedArticle);
}
}
public void getFirst() {
selectedArticles.clear();
initData();
}
@Override
public int getItemCount() {
return selectedArticles.size();
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
SelectedRecyclerHolder holder = (SelectedRecyclerHolder) viewHolder;
SelectedArticle selectedArticle = selectedArticles.get(position);
holder.title.setText(selectedArticle.getTitle());
holder.like.setText("" + selectedArticle.getLikeNumber());
holder.comment.setText("" + selectedArticle.getCommentNumber());
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewHolder, int position) {
View view = inflater.inflate(R.layout.fragment_selected_item, null);
return new SelectedRecyclerHolder(view);
}
public class SelectedRecyclerHolder extends RecyclerView.ViewHolder {
private TextView title;//標題
private TextView like;//喜歡數量
private TextView comment;評論數量
public SelectedRecyclerHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.tv_title);
like = (TextView) view.findViewById(R.id.tv_like);
comment = (TextView) view.findViewById(R.id.tv_comment);
}
}
}
在MainFragment裡面進行監聽
appBarLayout= (AppBarLayout) rootView.findViewById(R.id.appBarLayout);
appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);
然後在回調函數中,把值給SelectedFragment,
private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener=new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i){
//i>=0 Toolbar全部顯示
selectedFragment.setPullRefresh(i>=0);
System.out.println("i值:"+i);
}
};
3).在SelectedFragment中,繼續把值傳給PtrFrameLayout
public void setPullRefresh(boolean pullRefresh) {
ptrClassicFrameLayout.setPullRefresh(pullRefresh);
}
4.在PtrFrameLayout裡面用一個實例變量接收這個值
private boolean pullRefresh=true;
public void setPullRefresh(boolean pullRefresh) {
this.pullRefresh = pullRefresh;
}
4).找到PtrFrameLayout類的dispatchTouchEvent事件,這個方法是處理屏幕的觸摸事件的。
@Override
public boolean dispatchTouchEvent(MotionEvent e) {
if (!isEnabled() || mContent == null || mHeaderView == null) {
System.out.println("都是空的...");
return dispatchTouchEventSupper(e);
}
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
System.out.println("彈起...");
case MotionEvent.ACTION_CANCEL:
System.out.println("取消...");
// if(pullRefresh){
mPtrIndicator.onRelease();
if (mPtrIndicator.hasLeftStartPosition()) {
if (DEBUG) {
PtrCLog.d(LOG_TAG, "call onRelease when user release");
}
System.out.println("call onRelease when user release");
onRelease(false);
if (mPtrIndicator.hasMovedAfterPressedDown()) {
sendCancelEvent();
return true;
}
}
return dispatchTouchEventSupper(e);
// }
case MotionEvent.ACTION_DOWN:
System.out.println("按下...");
mHasSendCancelEvent = false;
mPtrIndicator.onPressDown(e.getX(), e.getY());
mScrollChecker.abortIfWorking();
mPreventForHorizontal = false;
// The cancel event will be sent once the position is moved.
// So let the event pass to children.
// fix #93, #102
return dispatchTouchEventSupper(e);
case MotionEvent.ACTION_MOVE:
System.out.println("移動...");
if(pullRefresh){//Toolbar顯示
mLastMoveEvent = e;
mPtrIndicator.onMove(e.getX(), e.getY());
float offsetX = mPtrIndicator.getOffsetX();
float offsetY = mPtrIndicator.getOffsetY();
if (mDisableWhenHorizontalMove && !mPreventForHorizontal && (Math.abs(offsetX) > mPagingTouchSlop && Math.abs(offsetX) > Math.abs(offsetY))) {
if (mPtrIndicator.isInStartPosition()) {
mPreventForHorizontal = true;
}
}
if (mPreventForHorizontal) {
return dispatchTouchEventSupper(e);
}
boolean moveDown = offsetY > 0;
boolean moveUp = !moveDown;
boolean canMoveUp = mPtrIndicator.hasLeftStartPosition();
if (DEBUG) {
boolean canMoveDown = mPtrHandler != null && mPtrHandler.checkCanDoRefresh(this, mContent, mHeaderView);
PtrCLog.v(LOG_TAG, "ACTION_MOVE: offsetY:%s, currentPos: %s, moveUp: %s, canMoveUp: %s, moveDown: %s: canMoveDown: %s", offsetY, mPtrIndicator.getCurrentPosY(), moveUp, canMoveUp, moveDown, canMoveDown);
}
// disable move when header not reach top
if (moveDown && mPtrHandler != null && !mPtrHandler.checkCanDoRefresh(this, mContent, mHeaderView)) {
return dispatchTouchEventSupper(e);
}
if ((moveUp && canMoveUp) || moveDown) {
// System.out.println("是否下拉刷新:"+pullRefresh+"偏移量是多少:"+offsetY);
movePos(offsetY);
return true;
}
}
}
return dispatchTouchEventSupper(e);
}
我就改了一行代碼,在action==MotionEvent.ACTION_MOVE的時候,先判斷我們傳入的pullRefresh是否為true。。。
頂部加入輪播1).得有一個保存View的集合,其實用一個變量也行,因為我們只有一個輪播View.
private List mCarouse = new ArrayList();//保存輪播View
//可以添加輪播View
public void addCarouse(View view){
mCarouse.add(view);
}
2).定義一個常量,用於類型判斷
public static final int TYPE_CAROUSE = 7900;
3).在getItemViewType裡面加入輪播的類型
@Override
public final int getItemViewType(int position) {
// check what type our position is, based on the assumption that the
// order is headers > items > footers
if (isHeader(position)) {
return TYPE_HEADER;
} else if (mCarouse.size()>0&&mHeaders.size()==position){ //判斷集合個數&&position==0 這個時候mHeaders裡面是沒有值的
return TYPE_CAROUSE;
}else if (isFooter(position)) {
return TYPE_FOOTER;
}
int type = getItemViewTypeHF(getRealPosition(position));
if (type == TYPE_HEADER || type == TYPE_FOOTER|| type == TYPE_CAROUSE) {
throw new IllegalArgumentException("Item type cannot equal " + TYPE_HEADER + " or " + TYPE_FOOTER);
}
return type;
}
4).onCreateViewHolder裡面也要修改一下,就是在if裡面多加了個&&.無論是頭部,底部,輪播的View,都是添加到FrameLayout裡面的。
@Override
public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
// if our position is one of our items (this comes from
// getItemViewType(int position) below)
if (type != TYPE_HEADER && type != TYPE_FOOTER && type != TYPE_CAROUSE) {
ViewHolder vh = onCreateViewHolderHF(viewGroup, type);
return vh;
// else we have a header/footer
} else {
// create a new framelayout, or inflate from a resource
FrameLayout frameLayout = new FrameLayout(viewGroup.getContext());
// make sure it fills the space
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return new HeaderFooterViewHolder(frameLayout);
}
}
5).onBindViewHolder這裡為item綁定數據,其實就是第四步返回的ItemView綁定數據.
@Override
public final void onBindViewHolder(final RecyclerView.ViewHolder vh, int position){
// check what type of view our position is
if (isHeader(position)) {
View v = mHeaders.get(position);
// add our view to a header view and display it
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
}else if(mCarouse.size()>0&&position==mHeaders.size()){//這個時候mHeaders.size()值為0
// System.out.println("有多少個頭View:"+mHeaders.size()+"值等於多少:"+(mHeaders.size()-1));
View v = mCarouse.get(mHeaders.size());//取出輪播的View
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
} else if (isFooter(position)) {
View v = mFooters.get(position - getItemCountHF() - mHeaders.size());
// add our view to a footer view and display it
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
} else {
vh.itemView.setOnClickListener(new MyOnClickListener(vh));
vh.itemView.setOnLongClickListener(new MyOnLongClickListener(vh));
// it's one of our items, display as required
onBindViewHolderHF(vh, getRealPosition(position));
}
}
6).我們從第五步看到頭部底部輪播View最後都會調用prepareHeaderFooter方法。看到這方法的源碼,其實就是把類型對應的View,添加到Item中.
private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view) {
// if it's a staggered grid, span the whole layout
if (mManagerType == TYPE_MANAGER_STAGGERED_GRID) {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
vh.itemView.setLayoutParams(layoutParams);
}
// if the view already belongs to another layout, remove it
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
// empty out our FrameLayout and replace with our header/footer
vh.base.removeAllViews();
vh.base.addView(view);
}
最近項目用到了藍牙連接,搜索設備的內容,其中需要搜索過程中出現波紋的動畫效果,在這裡將項目中OC語言編寫的這種動畫效果,轉換成Swift編寫,下面簡單介紹說明一下代碼。這
MIUI 8公測之後,MIUI官方微博隔一段時間就會將米粉集中反饋的問題以長微博的形式進行解答,同時爆料一些MIUI的新功能。繼上次透露MIUI 8將新增手
在Android中和我們打交道最多的就是Activity,因為我們會頻繁的與界面進行交互,而Activity內部關於界面方面的操作都是由Window來實現的,因此我們有必
需求:自定義一個ViewGroup,實現可以下拉刷新的功能。下拉一定距離後(下拉時顯示的界面可以自定義任何復雜的界面)釋放手指可以回調刷新的功能,用戶處理完刷新的內容後,