Android 에서 ListView 드 롭 다운 새로 고침 의 실현 방법

ListView 의 드 롭 다운 리 셋 은 매우 흔히 볼 수 있 고 자주 사용 합 니 다.많은 친구 들 이 원 하 는 것 을 보면 제 가 정리 해서 참고 하도록 하 겠 습 니 다.그럼 설명 하지 않 고 코드 를 바로 넣 겠 습 니 다.

ListView 를 다시 써 야 합 니 다.코드 를 다시 쓰 려 면 다음 과 같 습 니 다.

package net.loonggg.listview; 
 
import java.util.Date; 
 
import android.content.Context; 
import android.util.AttributeSet; 
import android.view.LayoutInflater; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.animation.LinearInterpolator; 
import android.view.animation.RotateAnimation; 
import android.widget.AbsListView; 
import android.widget.AbsListView.OnScrollListener; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.ListView; 
import android.widget.ProgressBar; 
import android.widget.TextView; 
 
public class MyListView extends ListView implements OnScrollListener { 
 
 private final static int RELEASE_To_REFRESH = 0;//          
 private final static int PULL_To_REFRESH = 1; //               
 private final static int REFRESHING = 2;//          
 private final static int DONE = 3; 
 private final static int LOADING = 4; 
 
 //    padding               
 private final static int RATIO = 3; 
 private LayoutInflater inflater; 
 
 // ListView          
 private LinearLayout headerView; 
 private TextView lvHeaderTipsTv; 
 private TextView lvHeaderLastUpdatedTv; 
 private ImageView lvHeaderArrowIv; 
 private ProgressBar lvHeaderProgressBar; 
 
 //                
 private int headerContentHeight; 
 
 private RotateAnimation animation; 
 private RotateAnimation reverseAnimation; 
 
 private int startY; 
 private int state; 
 private boolean isBack; 
 
 //     startY        touch          
 private boolean isRecored; 
 
 private OnRefreshListener refreshListener; 
 
 private boolean isRefreshable; 
 
 public MyListView(Context context) { 
  super(context); 
  init(context); 
 } 
 
 public MyListView(Context context, AttributeSet attrs) { 
  super(context, attrs); 
  init(context); 
 } 
 
 private void init(Context context) { 
  setCacheColorHint(context.getResources().getColor(R.color.transparent)); 
  inflater = LayoutInflater.from(context); 
  headerView = (LinearLayout) inflater.inflate(R.layout.lv_header, null); 
  lvHeaderTipsTv = (TextView) headerView 
    .findViewById(R.id.lvHeaderTipsTv); 
  lvHeaderLastUpdatedTv = (TextView) headerView 
    .findViewById(R.id.lvHeaderLastUpdatedTv); 
 
  lvHeaderArrowIv = (ImageView) headerView 
    .findViewById(R.id.lvHeaderArrowIv); 
  //                  
  lvHeaderArrowIv.setMinimumWidth(70); 
  lvHeaderArrowIv.setMinimumHeight(50); 
 
  lvHeaderProgressBar = (ProgressBar) headerView 
    .findViewById(R.id.lvHeaderProgressBar); 
  measureView(headerView); 
  headerContentHeight = headerView.getMeasuredHeight(); 
  //      ,                  ,        
  headerView.setPadding(0, -1 * headerContentHeight, 0, 0); 
  //      
  headerView.invalidate(); 
  //           ListView    
  addHeaderView(headerView, null, false); 
  //          
  setOnScrollListener(this); 
 
  //          
  animation = new RotateAnimation(0, -180, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f); 
  animation.setInterpolator(new LinearInterpolator()); 
  animation.setDuration(250); 
  animation.setFillAfter(true); 
 
  reverseAnimation = new RotateAnimation(-180, 0, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f); 
  reverseAnimation.setInterpolator(new LinearInterpolator()); 
  reverseAnimation.setDuration(200); 
  reverseAnimation.setFillAfter(true); 
 
  //                 ,   DONE 
  state = DONE; 
  //        
  isRefreshable = false; 
 } 
 
 @Override 
 public void onScrollStateChanged(AbsListView view, int scrollState) { 
 
 } 
 
 @Override 
 public void onScroll(AbsListView view, int firstVisibleItem, 
   int visibleItemCount, int totalItemCount) { 
    if (firstVisibleItem == 0) { 
     isRefreshable = true; 
     } else { 
     isRefreshable = false; 
     }  
  } 
 
 @Override 
 public boolean onTouchEvent(MotionEvent ev) { 
  if (isRefreshable) { 
   switch (ev.getAction()) { 
   case MotionEvent.ACTION_DOWN: 
    if (!isRecored) { 
     isRecored = true; 
     startY = (int) ev.getY();//             
    } 
    break; 
   case MotionEvent.ACTION_UP: 
    if (state != REFRESHING && state != LOADING) { 
     if (state == PULL_To_REFRESH) { 
      state = DONE; 
      changeHeaderViewByState(); 
     } 
     if (state == RELEASE_To_REFRESH) { 
      state = REFRESHING; 
      changeHeaderViewByState(); 
      onLvRefresh(); 
     } 
    } 
    isRecored = false; 
    isBack = false; 
 
    break; 
 
   case MotionEvent.ACTION_MOVE: 
    int tempY = (int) ev.getY(); 
    if (!isRecored) { 
     isRecored = true; 
     startY = tempY; 
    } 
    if (state != REFRESHING && isRecored && state != LOADING) { 
     //      padding    ,         head,             ,       ,          
     //          
     if (state == RELEASE_To_REFRESH) { 
      setSelection(0); 
      //     ,         head   ,               
      if (((tempY - startY) / RATIO < headerContentHeight)//                  
        && (tempY - startY) > 0) { 
       state = PULL_To_REFRESH; 
       changeHeaderViewByState(); 
      } 
      //         
      else if (tempY - startY <= 0) {//           done   
       state = DONE; 
       changeHeaderViewByState(); 
      } 
     } 
     //               ,DONE   PULL_To_REFRESH   
     if (state == PULL_To_REFRESH) { 
      setSelection(0); 
      //        RELEASE_TO_REFRESH    
      if ((tempY - startY) / RATIO >= headerContentHeight) {//  done                
       state = RELEASE_To_REFRESH; 
       isBack = true; 
       changeHeaderViewByState(); 
      } 
      //       
      else if (tempY - startY <= 0) {//  DOne           done   
       state = DONE; 
       changeHeaderViewByState(); 
      } 
     } 
     // done    
     if (state == DONE) { 
      if (tempY - startY > 0) { 
       state = PULL_To_REFRESH; 
       changeHeaderViewByState(); 
      } 
     } 
     //   headView size 
     if (state == PULL_To_REFRESH) { 
      headerView.setPadding(0, -1 * headerContentHeight 
        + (tempY - startY) / RATIO, 0, 0); 
 
     } 
     //   headView paddingTop 
     if (state == RELEASE_To_REFRESH) { 
      headerView.setPadding(0, (tempY - startY) / RATIO 
        - headerContentHeight, 0, 0); 
     } 
 
    } 
    break; 
 
   default: 
    break; 
   } 
  } 
  return super.onTouchEvent(ev); 
 } 
 
 //        ,     ,      
 private void changeHeaderViewByState() { 
  switch (state) { 
  case RELEASE_To_REFRESH: 
   lvHeaderArrowIv.setVisibility(View.VISIBLE); 
   lvHeaderProgressBar.setVisibility(View.GONE); 
   lvHeaderTipsTv.setVisibility(View.VISIBLE); 
   lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
 
   lvHeaderArrowIv.clearAnimation();//      
   lvHeaderArrowIv.startAnimation(animation);//        
 
   lvHeaderTipsTv.setText("    "); 
   break; 
  case PULL_To_REFRESH: 
   lvHeaderProgressBar.setVisibility(View.GONE); 
   lvHeaderTipsTv.setVisibility(View.VISIBLE); 
   lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
   lvHeaderArrowIv.clearAnimation(); 
   lvHeaderArrowIv.setVisibility(View.VISIBLE); 
   //   RELEASE_To_REFRESH       
   if (isBack) { 
    isBack = false; 
    lvHeaderArrowIv.clearAnimation(); 
    lvHeaderArrowIv.startAnimation(reverseAnimation); 
 
    lvHeaderTipsTv.setText("    "); 
   } else { 
    lvHeaderTipsTv.setText("    "); 
   } 
   break; 
 
  case REFRESHING: 
 
   headerView.setPadding(0, 0, 0, 0); 
 
   lvHeaderProgressBar.setVisibility(View.VISIBLE); 
   lvHeaderArrowIv.clearAnimation(); 
   lvHeaderArrowIv.setVisibility(View.GONE); 
   lvHeaderTipsTv.setText("    ..."); 
   lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
   break; 
  case DONE: 
   headerView.setPadding(0, -1 * headerContentHeight, 0, 0); 
 
   lvHeaderProgressBar.setVisibility(View.GONE); 
   lvHeaderArrowIv.clearAnimation(); 
   lvHeaderArrowIv.setImageResource(R.drawable.arrow); 
   lvHeaderTipsTv.setText("    "); 
   lvHeaderLastUpdatedTv.setVisibility(View.VISIBLE); 
   break; 
  } 
 } 
 
 //                    demo,   “  ”headView width  height 
 private void measureView(View child) { 
  ViewGroup.LayoutParams params = child.getLayoutParams(); 
  if (params == null) { 
   params = new ViewGroup.LayoutParams( 
     ViewGroup.LayoutParams.FILL_PARENT, 
     ViewGroup.LayoutParams.WRAP_CONTENT); 
  } 
  int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, 
    params.width); 
  int lpHeight = params.height; 
  int childHeightSpec; 
  if (lpHeight > 0) { 
   childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, 
     MeasureSpec.EXACTLY); 
  } else { 
   childHeightSpec = MeasureSpec.makeMeasureSpec(0, 
     MeasureSpec.UNSPECIFIED); 
  } 
  child.measure(childWidthSpec, childHeightSpec); 
 } 
 
 public void setonRefreshListener(OnRefreshListener refreshListener) { 
  this.refreshListener = refreshListener; 
  isRefreshable = true; 
 } 
 
 public interface OnRefreshListener { 
  public void onRefresh(); 
 } 
 
 public void onRefreshComplete() { 
  state = DONE; 
  lvHeaderLastUpdatedTv.setText("    :" + new Date().toLocaleString()); 
  changeHeaderViewByState(); 
 } 
 
 private void onLvRefresh() { 
  if (refreshListener != null) { 
   refreshListener.onRefresh(); 
  } 
 } 
 
 public void setAdapter(LvAdapter adapter) { 
  lvHeaderLastUpdatedTv.setText("    :" + new Date().toLocaleString()); 
  super.setAdapter(adapter); 
 } 
 
} 
ListView 를 다시 쓴 후 레이아웃 파일 에서 이렇게 사 용 됩 니 다.머리 밑 에서 새로 고침 한 레이아웃 파일 lvheader.xml 코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?> 
<!-- ListView    --> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content" 
 android:background="#000000" > 
 
 <!--    --> 
 
 <RelativeLayout 
  android:id="@+id/head_contentLayout" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:paddingLeft="30dp" > 
 
  <!--     、    --> 
 
  <FrameLayout 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:layout_alignParentLeft="true" 
   android:layout_centerVertical="true" > 
 
   <!--    --> 
 
   <ImageView 
    android:id="@+id/lvHeaderArrowIv" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:src="@drawable/arrow" /> 
 
   <!--     --> 
 
   <ProgressBar 
    android:id="@+id/lvHeaderProgressBar" 
    style="?android:attr/progressBarStyleSmall" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:visibility="gone" /> 
  </FrameLayout> 
 
  <!--   、     --> 
 
  <LinearLayout 
   android:layout_width="wrap_content" 
   android:layout_height="wrap_content" 
   android:layout_centerHorizontal="true" 
   android:gravity="center_horizontal" 
   android:orientation="vertical" > 
 
   <!--    --> 
 
   <TextView 
    android:id="@+id/lvHeaderTipsTv" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="    " 
    android:textColor="@color/white" 
    android:textSize="20sp" /> 
 
   <!--      --> 
 
   <TextView 
    android:id="@+id/lvHeaderLastUpdatedTv" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="    " 
    android:textColor="@color/gold" 
    android:textSize="10sp" /> 
  </LinearLayout> 
 </RelativeLayout> 
 
</LinearLayout> 
Main.xml 에서 설정 합 니 다.코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:background="#000000" 
 android:orientation="vertical" > 
 
 <net.loonggg.listview.MyListView 
  android:id="@+id/lv" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" /> 
 
</LinearLayout> 
그 다음 에 MainActivity 에서 이 루어 집 니 다.코드 는 다음 과 같 습 니 다.

package net.loonggg.listview; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import net.loonggg.listview.MyListView.OnRefreshListener; 
import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 
 
public class MainActivity extends Activity { 
 private List<String> list; 
 private MyListView lv; 
 private LvAdapter adapter; 
 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  lv = (MyListView) findViewById(R.id.lv); 
  list = new ArrayList<String>(); 
  list.add("loonggg"); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  list.add("       "); 
  adapter = new LvAdapter(list, this); 
  lv.setAdapter(adapter); 
 
  lv.setonRefreshListener(new OnRefreshListener() { 
 
   @Override 
   public void onRefresh() { 
    new AsyncTask<Void, Void, Void>() { 
     protected Void doInBackground(Void... params) { 
      try { 
       Thread.sleep(1000); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      list.add("        "); 
      return null; 
     } 
 
     @Override 
     protected void onPostExecute(Void result) { 
      adapter.notifyDataSetChanged(); 
      lv.onRefreshComplete(); 
     } 
    }.execute(null, null, null); 
   } 
  }); 
 } 
} 
ListView 에 Adapter 를 설정 해 야 합 니 다.사용자 정의 Adapter 는 다음 과 같 습 니 다.

package net.loonggg.listview; 
 
import java.util.List; 
 
import android.content.Context; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 
 
public class LvAdapter extends BaseAdapter { 
 private List<String> list; 
 private Context context; 
 
 public LvAdapter(List<String> list, Context context) { 
  this.list = list; 
  this.context = context; 
 } 
 
 @Override 
 public int getCount() { 
  return list.size(); 
 } 
 
 @Override 
 public Object getItem(int position) { 
  return list.get(position); 
 } 
 
 @Override 
 public long getItemId(int position) { 
  return position; 
 } 
 
 @Override 
 public View getView(int position, View convertView, ViewGroup parent) { 
  TextView tv = new TextView(context.getApplicationContext()); 
  tv.setText(list.get(position)); 
  return tv; 
 } 
 
} 
안 드 로 이 드 리 스 트 뷰 를 대상 으로 깊이 연구 하고 싶 은 학생 은 주 제 를 참고 할 수 있다<Android listview 사용 방법 집계>
여기까지 입 니 다.코드 중의 설명 이 매우 상세 합 니 다.구체 적 인 것 은 더 이상 말 하지 않 겠 습 니 다.설명 하지 않 겠 습 니 다.직접 보고 연구 하 세 요!

좋은 웹페이지 즐겨찾기