Android 사용자 정의 컨트롤 드 롭 다운 리 셋 인 스 턴 스 코드

구현 효과:

그림 소재:

-->우선 드 롭 다운 새로 고침 시 새로 고침 레이아웃 pullto_refresh.xml:

<resources>
  <string name="app_name">PullToRefreshTest</string>
  <string name="pull_to_refresh">      </string>
  <string name="release_to_refresh">      </string>
  <string name="refreshing">    ...</string>
  <string name="not_updated_yet">     </string>
  <string name="updated_at">     %1$s </string>
  <string name="updated_just_now">    </string>
  <string name="time_error">     </string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/pull_to_refresh_head"
  android:layout_width="match_parent"
  android:layout_height="60dp">
  <LinearLayout
    android:layout_width="200dp"
    android:layout_height="60dp"
    android:layout_centerInParent="true"
    android:orientation="horizontal">
    <RelativeLayout
      android:layout_width="0dp"
      android:layout_height="60dp"
      android:layout_weight="3">
      <ImageView
        android:id="@+id/arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@mipmap/indicator_arrow" />
      <ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerInParent="true"
        android:visibility="gone" />
    </RelativeLayout>
    <LinearLayout
      android:layout_width="0dp"
      android:layout_height="60dp"
      android:layout_weight="12"
      android:orientation="vertical">
      <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_horizontal|bottom"
        android:text="@string/pull_to_refresh" />
      <TextView
        android:id="@+id/updated_at"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_horizontal|top"
        android:text="@string/updated_at" />
    </LinearLayout>
  </LinearLayout>
</RelativeLayout>

strings
pull_to_refresh
-->   ,      ,          View (          ) RefreshView.java:
package com.dragon.android.tofreshlayout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class RefreshView extends LinearLayout implements View.OnTouchListener {
private static final String TAG = RefreshView.class.getSimpleName();
public enum PULL_STATUS {
STATUS_PULL_TO_REFRESH(0), //     
STATUS_RELEASE_TO_REFRESH(1), //         
STATUS_REFRESHING(2), //       
STATUS_REFRESH_FINISHED(3); //           
private int status; //   
PULL_STATUS(int value) {
this.status = value;
}
public int getValue() {
return this.status;
}
}
//          
public static final int SCROLL_SPEED = -20;
//        ,           
public static final long ONE_MINUTE = 60 * 1000;
//        ,           
public static final long ONE_HOUR = 60 * ONE_MINUTE;
//       ,           
public static final long ONE_DAY = 24 * ONE_HOUR;
//       ,           
public static final long ONE_MONTH = 30 * ONE_DAY;
//       ,           
public static final long ONE_YEAR = 12 * ONE_MONTH;
//             ,     SharedPreferences    
private static final String UPDATED_AT = "updated_at";
//          
private PullToRefreshListener mListener;
private SharedPreferences preferences; //           
private View header; //     View
private ListView listView; //         ListView
private ProgressBar progressBar; //          
private ImageView arrow; //           
private TextView description; //             
private TextView updateAt; //            
private MarginLayoutParams headerLayoutParams; //         
private long lastUpdateTime; //           
//                           ,  id    
private int mId = -1;
private int hideHeaderHeight; //       
/**
*         ,     STATUS_PULL_TO_REFRESH, STATUS_RELEASE_TO_REFRESH, STATUS_REFRESHING   STATUS_REFRESH_FINISHED
*/
private PULL_STATUS currentStatus = PULL_STATUS.STATUS_REFRESH_FINISHED;
//            ,        
private PULL_STATUS lastStatus = currentStatus;
private float yDown; //            
private int touchSlop; //                      。
private boolean loadOnce; //         layout,  onLayout           
private boolean ableToPull; //         ,  ListView            
/**
*            ,                 
*/
public RefreshView(Context context, AttributeSet attrs) {
super(context, attrs);
preferences = PreferenceManager.getDefaultSharedPreferences(context);
header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true);
progressBar = (ProgressBar) header.findViewById(R.id.progress_bar);
arrow = (ImageView) header.findViewById(R.id.arrow);
description = (TextView) header.findViewById(R.id.description);
updateAt = (TextView) header.findViewById(R.id.updated_at);
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
refreshUpdatedAtValue();
setOrientation(VERTICAL);
addView(header, 0);
//Log.d(TAG, "RefreshView Constructor() getChildAt(0): " + getChildAt(0));
//Log.d(TAG, "RefreshView Constructor() getChildAt(0): " + getChildAt(1));
// listView = (ListView) getChildAt(1);
// listView.setOnTouchListener(this);
}
/**
*              ,  :            ,  ListView    touch   
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (changed && !loadOnce) {
hideHeaderHeight = -header.getHeight();
headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
headerLayoutParams.topMargin = hideHeaderHeight;
listView = (ListView) getChildAt(1);
//Log.d(TAG, "onLayout() getChildAt(0): " + getChildAt(0));
//Log.d(TAG, "onLayout() listView: " + listView);
listView.setOnTouchListener(this);
loadOnce = true;
}
}
/**
*   ListView       ,                
*/
@Override
public boolean onTouch(View v, MotionEvent event) {
setCanAbleToPull(event); //         
if (ableToPull) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
yDown = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
//        Y     
float yMove = event.getRawY();
//                 
int distance = (int) (yMove - yDown);
//          ,           ,       
if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
return false;
}
if (distance < touchSlop) {
return false;
}
//            
if (currentStatus != PULL_STATUS.STATUS_REFRESHING) {
//       topMargin    > 0,         -header.getHeight()
if (headerLayoutParams.topMargin > 0) {
currentStatus = PULL_STATUS.STATUS_RELEASE_TO_REFRESH;
} else {
//            
currentStatus = PULL_STATUS.STATUS_PULL_TO_REFRESH;
}
//          topMargin  ,       
headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
header.setLayoutParams(headerLayoutParams);
}
break;
case MotionEvent.ACTION_UP:
default:
if (currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) {
//               ,           
new RefreshingTask().execute();
} else if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH) {
//           ,            
new HideHeaderTask().execute();
}
break;
}
//              
if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH
|| currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) {
updateHeaderView();
//             ,   ListView     ,                  
listView.setPressed(false);
listView.setFocusable(false);
listView.setFocusableInTouchMode(false);
lastStatus = currentStatus;
//             ,     true     ListView      
return true;
}
}
return false;
}
/**
*               
*
* @param listener       
* @param id                           ,                        id
*/
public void setOnRefreshListener(PullToRefreshListener listener, int id) {
mListener = listener;
mId = id;
}
/**
*            ,      ,     ListView            
*/
public void finishRefreshing() {
currentStatus = PULL_STATUS.STATUS_REFRESH_FINISHED;
preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit();
new HideHeaderTask().execute();
}
/**
*      ListView          {@link #ableToPull}
*   ,       onTouch       ,               ListView,        
*/
private void setCanAbleToPull(MotionEvent event) {
View firstChild = listView.getChildAt(0);
if (firstChild != null) {
//    ListView     Item   
int firstVisiblePos = listView.getFirstVisiblePosition();
//           Top        Item     
if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
if (!ableToPull) {
// getRawY()          Y      
yDown = event.getRawY();
}
//           ,        0,    ListView        ,          
ableToPull = true;
} else {
if (headerLayoutParams.topMargin != hideHeaderHeight) {
headerLayoutParams.topMargin = hideHeaderHeight;
header.setLayoutParams(headerLayoutParams);
}
ableToPull = false;
}
} else {
//    ListView      ,         
ableToPull = true;
}
}
/**
*          
*/
private void updateHeaderView() {
if (lastStatus != currentStatus) {
if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH) {
description.setText(getResources().getString(R.string.pull_to_refresh));
arrow.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
rotateArrow();
} else if (currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) {
description.setText(getResources().getString(R.string.release_to_refresh));
arrow.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
rotateArrow();
} else if (currentStatus == PULL_STATUS.STATUS_REFRESHING) {
description.setText(getResources().getString(R.string.refreshing));
progressBar.setVisibility(View.VISIBLE);
arrow.clearAnimation();
arrow.setVisibility(View.GONE);
}
refreshUpdatedAtValue();
}
}
/**
*             
*/
private void rotateArrow() {
float pivotX = arrow.getWidth() / 2f;
float pivotY = arrow.getHeight() / 2f;
float fromDegrees = 0f;
float toDegrees = 0f;
if (currentStatus == PULL_STATUS.STATUS_PULL_TO_REFRESH) {
fromDegrees = 180f;
toDegrees = 360f;
} else if (currentStatus == PULL_STATUS.STATUS_RELEASE_TO_REFRESH) {
fromDegrees = 0f;
toDegrees = 180f;
}
RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY);
animation.setDuration(100);
animation.setFillAfter(true);
arrow.startAnimation(animation);
}
/**
*                  
*/
private void refreshUpdatedAtValue() {
lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1);
long currentTime = System.currentTimeMillis();
long timePassed = currentTime - lastUpdateTime;
long timeIntoFormat;
String updateAtValue;
if (lastUpdateTime == -1) {
updateAtValue = getResources().getString(R.string.not_updated_yet);
} else if (timePassed < 0) {
updateAtValue = getResources().getString(R.string.time_error);
} else if (timePassed < ONE_MINUTE) {
updateAtValue = getResources().getString(R.string.updated_just_now);
} else if (timePassed < ONE_HOUR) {
timeIntoFormat = timePassed / ONE_MINUTE;
String value = timeIntoFormat + "  ";
updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
} else if (timePassed < ONE_DAY) {
timeIntoFormat = timePassed / ONE_HOUR;
String value = timeIntoFormat + "  ";
updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
} else if (timePassed < ONE_MONTH) {
timeIntoFormat = timePassed / ONE_DAY;
String value = timeIntoFormat + " ";
updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
} else if (timePassed < ONE_YEAR) {
timeIntoFormat = timePassed / ONE_MONTH;
String value = timeIntoFormat + "  ";
updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
} else {
timeIntoFormat = timePassed / ONE_YEAR;
String value = timeIntoFormat + " ";
updateAtValue = String.format(getResources().getString(R.string.updated_at), value);
}
updateAt.setText(updateAtValue);
}
/**
*        ,                     
*/
class RefreshingTask extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
int topMargin = headerLayoutParams.topMargin;
while (true) {
topMargin = topMargin + SCROLL_SPEED;
if (topMargin <= 0) {
topMargin = 0;
break;
}
publishProgress(topMargin);
SystemClock.sleep(10);
}
currentStatus = PULL_STATUS.STATUS_REFRESHING;
publishProgress(0);
if (mListener != null) {
mListener.onRefresh();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... topMargin) {
updateHeaderView();
headerLayoutParams.topMargin = topMargin[0];
header.setLayoutParams(headerLayoutParams);
}
}
/**
*         ,                ,             
*/
class HideHeaderTask extends AsyncTask<Void, Integer, Integer> {
@Override
protected Integer doInBackground(Void... params) {
int topMargin = headerLayoutParams.topMargin;
while (true) {
topMargin = topMargin + SCROLL_SPEED;
if (topMargin <= hideHeaderHeight) {
topMargin = hideHeaderHeight;
break;
}
publishProgress(topMargin);
SystemClock.sleep(10);
}
return topMargin;
}
@Override
protected void onProgressUpdate(Integer ... topMargin) {
headerLayoutParams.topMargin = topMargin[0];
header.setLayoutParams(headerLayoutParams);
}
@Override
protected void onPostExecute(Integer topMargin) {
headerLayoutParams.topMargin = topMargin;
header.setLayoutParams(headerLayoutParams);
currentStatus = PULL_STATUS.STATUS_REFRESH_FINISHED;
}
}
/**
*         ,                        
*/
public interface PullToRefreshListener {
//           ,             。              ,                
void onRefresh();
}
}
-->세 번 째 단계,메 인 레이아웃 쓰기:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
  tools:context=".MainActivity" >
  <com.dragon.android.tofreshlayout.RefreshView
    android:id="@+id/refreshable_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ListView
      android:id="@+id/list_view"
      android:layout_width="match_parent"
      android:layout_height="match_parent" >
    </ListView>
  </com.dragon.android.tofreshlayout.RefreshView>
</RelativeLayout>
-->마지막 으로 자바 코드 에 ListView 데 이 터 를 추가 합 니 다.

package com.dragon.android.tofreshlayout;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
  RefreshView refreshableView;
  ListView listView;
  ArrayAdapter<String> adapter;
  private WebView webView;
  private static int NUM = 30;
  String[] items = new String[NUM];
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();
    for (int i = 0; i < items.length; i++) {
      items[i] = "   " + i;
    }
    refreshableView = (RefreshView) findViewById(R.id.refreshable_view);
    listView = (ListView) findViewById(R.id.list_view);
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
    listView.setAdapter(adapter);
    refreshableView.setOnRefreshListener(new RefreshView.PullToRefreshListener() {
      @Override
      public void onRefresh() {
        SystemClock.sleep(3000);
        refreshableView.finishRefreshing();
      }
    }, 0);
  }
}
프로그램 데모:링크:http://pan.baidu.com/s/1ge6Llw3 비밀번호:skna
***************
위 에서 말 한 것 은 소 편 이 소개 한 안 드 로 이 드 사용자 정의 컨트롤 드 롭 다운 으로 인 스 턴 스 코드 를 새로 고침 하 는 것 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 면 메 시 지 를 남 겨 주세요.소 편 은 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기