안드로이드 개발(49) 안드로이드 드롭다운 리셋의 실현.pull-to-refesh 대신 SwipeRefresh Layout을 사용합니다

12675 단어
개술
구글은 드롭다운 쇄신 효과를 위해 스위프 리프레시 Layout을 공식 출시했다.이전에 우리가 자주 사용했던pull-to-refesh에 비해 이 방안은 더욱 간단하고 편리해 보인다.
 
관련 항목 참조(관리 종속)
응용 프로그램 수준의build입니다.gradle에 다음과 같이 추가됩니다.
   compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.android.support:support-v4:23.0.0'

 
레이아웃 작성(Layout)
<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"
    tools:context=".MainActivity">


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/listview1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

 
코드에 감청기 처리 이벤트 추가
  public void setOnRefreshListener(OnRefreshListener listener)
  

전체 코드
package demo.vir56k.swiperefreshlayoutdemo;

import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int REFRESH_COMPLETE = 0X110;
    private SwipeRefreshLayout mSwipeLayout;
    private ListView mListView;
    private ArrayAdapter<String> mAdapter;
    private List<String> mDatas;

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

        mListView = (ListView) findViewById(R.id.listview1);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout1);

        mDatas = creatDataSource();
        mSwipeLayout.setOnRefreshListener(mSwipeRefreshLayoutOnRefreshListener);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDatas);
        mListView.setAdapter(mAdapter);
    }

    private List<String> creatDataSource() {
        mDatas = new ArrayList<String>();
        for (int i = 0; i < 5; i++) {
            mDatas.add("item" + i);
        }
        return mDatas;
    }


    SwipeRefreshLayout.OnRefreshListener mSwipeRefreshLayoutOnRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000);
        }
    };

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_COMPLETE:
                    List<String> lst = new ArrayList<String>();
                    for (int i = mDatas.size() + 3; i > mDatas.size(); i--) {
                        lst.add("item -" + i);
                    }
                    mDatas.addAll(0, lst);
                    mAdapter.notifyDataSetChanged();
                    mSwipeLayout.setRefreshing(false);
                    break;

            }
        }

        ;
    };
}

이로써 완성하다.
 
보충:
다른 경우 "Swipe Refresh Layout의 하위 컨트롤은listview 등이 아니라 일반적인relativewlayout이면 어떻게 하나요?"
해결 방법: Swipe Refresh Layout을 계승하여 canchildScroll Up을 다시 쓰는 방법
 
/*
 * Copyright 2016, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.architecture.blueprints.todoapp.tasks;

import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.View;

/**
 * Extends {@link SwipeRefreshLayout} to support non-direct descendant scrolling views.
 * <p>
 * {@link SwipeRefreshLayout} works as expected when a scroll view is a direct child: it triggers
 * the refresh only when the view is on top. This class adds a way (@link #setScrollUpChild} to
 * define which view controls this behavior.
 */
public class ScrollChildSwipeRefreshLayout extends SwipeRefreshLayout {

    private View mScrollUpChild;

    public ScrollChildSwipeRefreshLayout(Context context) {
        super(context);
    }

    public ScrollChildSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean canChildScrollUp() {
        if (mScrollUpChild != null) {
            return ViewCompat.canScrollVertically(mScrollUpChild, -1);
        }
        return super.canChildScrollUp();
    }

    public void setScrollUpChild(View view) {
        mScrollUpChild = view;
    }
}

 
  
  

좋은 웹페이지 즐겨찾기