Android ListView 드롭다운 새로 고침 클릭하여 추가 로드
                                            
 22874 단어  ListView드롭다운 새로 고침추가 로드
                    
효과도
드롭다운 새로 고침:
추가 로드:
CustomListView.java
package com.example.uitest.view;
import java.util.Date;
import com.example.uitest.R;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
 * ListView    
 *
 */
public class CustomListView 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;
	private LinearLayout headView;
	private TextView tipsTextview;
	private TextView lastUpdatedTextView;
	private ImageView arrowImageView;
	private ProgressBar progressBar;
	private RotateAnimation animation;
	private RotateAnimation reverseAnimation;
	//     startY        touch         
	private boolean isRecored;
	private int headContentWidth;
	private int headContentHeight;
	private int startY;
	private int firstItemIndex;
	private int state;
	private boolean isBack;
	private OnRefreshListener refreshListener;
	private OnLoadListener loadListener;
	private boolean isRefreshable;
	
	private ProgressBar moreProgressBar;
	private TextView loadMoreView;
	private View moreView;
	public CustomListView(Context context) {
		super(context);
		init(context);
	}
	public CustomListView(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);
		headView = (LinearLayout) inflater.inflate(R.layout.head, null);
		arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView);
		arrowImageView.setMinimumWidth(70);
		arrowImageView.setMinimumHeight(50);
		progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar);
		tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);
		lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView);
		measureView(headView);
		headContentHeight = headView.getMeasuredHeight();
		headContentWidth = headView.getMeasuredWidth();
		headView.setPadding(0, -1 * headContentHeight, 0, 0);
		headView.invalidate();
		Log.v("size", "width:" + headContentWidth + " height:" + headContentHeight);
		addHeaderView(headView, 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);
		state = DONE;
		isRefreshable = false;
		
		moreView = LayoutInflater.from(context).inflate(R.layout.listfooter_more, null);
		moreView.setVisibility(View.VISIBLE);
		moreProgressBar = (ProgressBar) moreView.findViewById(R.id.pull_to_refresh_progress);
		loadMoreView = (TextView) moreView.findViewById(R.id.load_more);
		moreView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				onLoad();
			}
		});
		addFooterView(moreView);
	}
	public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2, int arg3) {
		firstItemIndex = firstVisiableItem;
	}
	public void onScrollStateChanged(AbsListView arg0, int arg1) {
		
	}
	public boolean onTouchEvent(MotionEvent event) {
		if (isRefreshable) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (firstItemIndex == 0 && !isRecored) {
					isRecored = true;
					startY = (int) event.getY();
				}
				break;
			case MotionEvent.ACTION_UP:
				if (state != REFRESHING && state != LOADING) {
					if (state == DONE) {
						
					}
					if (state == PULL_To_REFRESH) {
						state = DONE;
						changeHeaderViewByState();
					}
					if (state == RELEASE_To_REFRESH) {
						state = REFRESHING;
						changeHeaderViewByState();
						onRefresh();
					}
				}
				isRecored = false;
				isBack = false;
				break;
			case MotionEvent.ACTION_MOVE:
				int tempY = (int) event.getY();
				if (!isRecored && firstItemIndex == 0) {
					isRecored = true;
					startY = tempY;
				}
				if (state != REFRESHING && isRecored && state != LOADING) {
					//      padding    ,         head,             ,       ,         
					//         
					if (state == RELEASE_To_REFRESH) {
						setSelection(0);
						//     ,         head   ,              
						if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) {
							state = PULL_To_REFRESH;
							changeHeaderViewByState();
						}
						//        
						else if (tempY - startY <= 0) {
							state = DONE;
							changeHeaderViewByState();
						}
						//     ,              head   
					}
					//               ,DONE   PULL_To_REFRESH  
					if (state == PULL_To_REFRESH) {
						setSelection(0);
						//        RELEASE_TO_REFRESH   
						if ((tempY - startY) / RATIO >= headContentHeight) {
							state = RELEASE_To_REFRESH;
							isBack = true;
							changeHeaderViewByState();
						}
						else if (tempY - startY <= 0) {
							state = DONE;
							changeHeaderViewByState();
						}
					}
					if (state == DONE) {
						if (tempY - startY > 0) {
							state = PULL_To_REFRESH;
							changeHeaderViewByState();
						}
					}
					if (state == PULL_To_REFRESH) {
						headView.setPadding(0, -1 * headContentHeight + (tempY - startY) / RATIO, 0, 0);
					}
					if (state == RELEASE_To_REFRESH) {
						headView.setPadding(0, (tempY - startY) / RATIO - headContentHeight, 0, 0);
					}
				}
				break;
			}
		}
		return super.onTouchEvent(event);
	}
	//        ,     ,     
	private void changeHeaderViewByState() {
		switch (state) {
		case RELEASE_To_REFRESH:
			arrowImageView.setVisibility(View.VISIBLE);
			progressBar.setVisibility(View.GONE);
			tipsTextview.setVisibility(View.VISIBLE);
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.startAnimation(animation);
			tipsTextview.setText("    ");
			break;
		case PULL_To_REFRESH:
			progressBar.setVisibility(View.GONE);
			tipsTextview.setVisibility(View.VISIBLE);
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.setVisibility(View.VISIBLE);
			//   RELEASE_To_REFRESH      
			if (isBack) {
				isBack = false;
				arrowImageView.clearAnimation();
				arrowImageView.startAnimation(reverseAnimation);
				tipsTextview.setText("    ");
			} else {
				tipsTextview.setText("    ");
			}
			break;
		case REFRESHING:
			headView.setPadding(0, 0, 0, 0);
			progressBar.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.setVisibility(View.GONE);
			tipsTextview.setText("    ...");
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			break;
		case DONE:
			headView.setPadding(0, -1 * headContentHeight, 0, 0);
			progressBar.setVisibility(View.GONE);
			arrowImageView.clearAnimation();
			arrowImageView.setImageResource(R.drawable.arrow);
			tipsTextview.setText("    ");
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			break;
		}
	}
	public void setonRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
		isRefreshable = true;
	}
	
	public void setonLoadListener(OnLoadListener loadListener) {
		this.loadListener = loadListener;
	}
	public interface OnRefreshListener {
		public void onRefresh();
	}
	
	public interface OnLoadListener {
		public void onLoad();
	}
	@SuppressWarnings("deprecation")
	public void onRefreshComplete() {
		state = DONE;
		lastUpdatedTextView.setText("    :" + new Date().toLocaleString());
		changeHeaderViewByState();
	}
	
	private void onLoad() {
		if (loadListener != null) {
			moreProgressBar.setVisibility(View.VISIBLE);
			loadMoreView.setText(getContext().getString(R.string.load_more));
			loadListener.onLoad();
		}
	}
	
	public void onLoadComplete() {
//		moreView.setVisibility(View.GONE);
		moreProgressBar.setVisibility(View.GONE);
		loadMoreView.setText(getContext().getString(R.string.more_data));
	}
	private void onRefresh() {
		if (refreshListener != null) {
			refreshListener.onRefresh();
		}
	}
	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}
	@SuppressWarnings("deprecation")
	public void setAdapter(BaseAdapter adapter) {
		lastUpdatedTextView.setText("    :" + new Date().toLocaleString());
		super.setAdapter(adapter);
	}
}
Custom ListView에는 2개의 리셋 인터페이스가 있는데, OnRefresh Listener와 OnLoad Listener는 각각 밑에 있는 것과 누르면 더 많은 리셋 함수를 불러옵니다.드롭다운 새로 고침이 완료되면 mListView를 호출합니다.onRefreshComplete(); 자, 머리를 숨기고 mListView를 호출하십시오.onLoadComplete(); 밑에 있는 불러오기view를 숨깁니다.
header.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" >
    <!--    -->
    <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/head_arrowImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:contentDescription="@string/app_name"
                android:src="@drawable/arrow" />
            <!--     -->
            <ProgressBar
                android:id="@+id/head_progressBar"
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:indeterminateDrawable="@drawable/progressbar_bg"
                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/head_tipsTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/pull_to_refresh_pull_label"
                android:textColor="@color/pull_refresh_textview"
                android:textSize="20sp" />
            <!--      -->
            <TextView
                android:id="@+id/head_lastUpdatedTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/pull_to_refresh_refresh_lasttime"
                android:textColor="@color/gold"
                android:textSize="10sp" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>listfooter_more.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:gravity="center_horizontal"
    android:orientation="horizontal"
    android:padding="15dp"
     >
    <ProgressBar
        android:id="@+id/pull_to_refresh_progress"
        style="@android:style/Widget.ProgressBar.Small.Inverse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:indeterminate="true"
        android:visibility="gone" >
    </ProgressBar>
    <TextView
        android:id="@+id/load_more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10.0dp"
        android:gravity="center"
        android:text="@string/more_data"
        android:textColor="@color/black" >
    </TextView>
</LinearLayout>MainActivity.java
package com.example.uitest;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.uitest.model.AppInfo;
import com.example.uitest.view.CustomListView;
import com.example.uitest.view.CustomListView.OnLoadListener;
import com.example.uitest.view.CustomListView.OnRefreshListener;
public class MainActivity extends Activity {
	
	private static final String TAG = MainActivity.class.getSimpleName();
	private static final int LOAD_DATA_FINISH = 10;
	private static final int REFRESH_DATA_FINISH = 11;
	
	private List<AppInfo> mList = new ArrayList<AppInfo>();
	private CustomListAdapter mAdapter;
	private CustomListView mListView;
	private int count = 10;
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case REFRESH_DATA_FINISH:
				
				if(mAdapter!=null){
					mAdapter.notifyDataSetChanged();
				}
				mListView.onRefreshComplete();	//      
				break;
			case LOAD_DATA_FINISH:
				if(mAdapter!=null){
					mAdapter.notifyDataSetChanged();
				}
				mListView.onLoadComplete();	//      
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		buildAppData();
		
		mAdapter = new CustomListAdapter(this);
		mListView = (CustomListView) findViewById(R.id.mListView);
		mListView.setAdapter(mAdapter);
		
		mListView.setonRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				//TODO     
				Log.e(TAG, "onRefresh");
				loadData(0);
			}
		});
		
		mListView.setonLoadListener(new OnLoadListener() {
			
			@Override
			public void onLoad() {
				//TODO     
				Log.e(TAG, "onLoad");
				loadData(1);
			}
		});
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.e(TAG, "click position:" + position);
			}
		});
	}
	
	public void loadData(final int type){
		new Thread(){
			@Override
			public void run() {
				
				for(int i=count;i<count+10;i++){
					AppInfo ai = new AppInfo();
					ai.setAppIcon(BitmapFactory.decodeResource(getResources(),
							R.drawable.ic_launcher));
					ai.setAppName("  Demo_" + i);
					ai.setAppVer("  : " + (i % 10 + 1) + "." + (i % 8 + 2) + "."
							+ (i % 6 + 3));
					ai.setAppSize("  : " + i * 10 + "MB");
					mList.add(ai);
				}
				count += 10;
				
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				if(type==0){	//    
//					Collections.reverse(mList);	//  
					handler.sendEmptyMessage(REFRESH_DATA_FINISH);
				}else if(type==1){
					handler.sendEmptyMessage(LOAD_DATA_FINISH);
				}
				
			}
		}.start();
	}
	
	/**
	 *        
	 */
	private void buildAppData() {
		for (int i = 0; i < 10; i++) {
			AppInfo ai = new AppInfo();
			ai.setAppIcon(BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_launcher));
			ai.setAppName("  Demo_" + i);
			ai.setAppVer("  : " + (i % 10 + 1) + "." + (i % 8 + 2) + "."
					+ (i % 6 + 3));
			ai.setAppSize("  : " + i * 10 + "MB");
			mList.add(ai);
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public class CustomListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		public CustomListAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			return mList.size();
		}
		@Override
		public Object getItem(int arg0) {
			return mList.get(arg0);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (getCount() == 0) {
				return null;
			}
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.ivImage = (ImageView) convertView
						.findViewById(R.id.ivIcon);
				holder.tvName = (TextView) convertView
						.findViewById(R.id.tvName);
				holder.tvVer = (TextView) convertView.findViewById(R.id.tvVer);
				holder.tvSize = (TextView) convertView
						.findViewById(R.id.tvSize);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			AppInfo ai = mList.get(position);
			holder.ivImage.setImageBitmap(ai.getAppIcon());
			holder.tvName.setText(ai.getAppName());
			holder.tvVer.setText(ai.getAppVer());
			holder.tvSize.setText(ai.getAppSize());
			return convertView;
		}
	}
	public static class ViewHolder {
		private ImageView ivImage;
		private TextView tvName;
		private TextView tvVer;
		private TextView tvSize;
	}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id/ivIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/image_desc"
        android:src="@drawable/ic_launcher" />
    <LinearLayout
        android:id="@+id/appInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dip"
        android:layout_toRightOf="@id/ivIcon"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:textColor="#000000"
            android:textSize="16sp" />
        <TextView
            android:id="@+id/tvVer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/ver"
            android:textColor="#666666"
            android:textSize="13sp" />
        <TextView
            android:id="@+id/tvSize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/size"
            android:textColor="#666666"
            android:textSize="13sp" />
    </LinearLayout>
    <Button
        android:id="@+id/btnClick"
        android:layout_width="80dip"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:focusable="false"
        android:text="@string/mgr"
        android:textColor="#000000"
        android:textSize="16sp" />
</RelativeLayout>프로젝트 다운로드 주소:http://download.csdn.net/detail/fx_sky/5646017
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Flutter의 ListTile에서 높이를 지정하면 레이아웃이 무너지는 문제현재 업무로 1개월 반 정도 Flutter를 사용하고 있습니다. 아주 좋은 팀으로, 최근에는 Flutter 자체에도 열중해 왔습니다. title, subtitle, leading, trailing 등을 설정하는 것만...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.