編輯:關於Android編程
Android實現功能:Listview嵌套viewpager仿淘寶搜狐視頻主頁面,和listview的下拉刷新。
直接上圖
下面給出我源碼的主要文件構成:
MyListView文件:
主要功能重寫listview實現下拉刷新
package com.example.com.xiyouliwp.demo;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.Date;
/**
* Created by lwp940118 on 2016/5/13.
* 需求:重寫listview實現下拉刷新
* 李文朋
*/
public class MyListView extends ListView implements AbsListView.OnScrollListener {
private boolean isRecored;
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 OnRefreshListener refreshListener;
//下拉刷新的控件定義
private TextView textView_recommend_old;
private TextView textView_recommend_new;
private ImageView imageView_recommend_refresh;
private ProgressBar progressBar_recommend_refresh;
private int startY;
private int firstItemIndex;
private LayoutInflater inflater;
private LinearLayout layout;
//定義下拉刷新顯示的東西的寬高
private int headContentWidth;
private int headContentHeight;
private RotateAnimation animation;
private RotateAnimation reverseAnimation;
private int state;
private boolean isRefreshable;
private boolean isBack;
public MyListView(Context context) {
super(context);
inti(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
inti(context);
}
private void inti(Context context) {
setCacheColorHint(context.getResources().getColor(R.color.transparent));
inflater = LayoutInflater.from(context);
layout = (LinearLayout) inflater.inflate(R.layout.mylistview_shuaxin, null);
textView_recommend_new = (TextView) layout.findViewById(R.id.textview_recommend_refresh_new);
textView_recommend_old = (TextView) layout.findViewById(R.id.textview_recommend_refresh_old);
imageView_recommend_refresh = (ImageView) layout.findViewById(R.id.imgeview_recommend_refresh);
progressBar_recommend_refresh = (ProgressBar) layout.findViewById(R.id.progressbar_recommend_refrsh);
//設置下拉刷新圖標的寬高
imageView_recommend_refresh.setMinimumHeight(50);
imageView_recommend_refresh.setMinimumWidth(70);
measureView(layout);
headContentHeight = layout.getMeasuredHeight();
headContentWidth = layout.getMeasuredWidth();
layout.setPadding(0, -1 * headContentHeight, 0, 0);
layout.invalidate();
Log.v("size", "width:" + headContentWidth + " height:"
+ headContentHeight);
addHeaderView(layout, 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;
}
@Override
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的地步
else {
// 不用進行特別的操作,只用更新paddingTop的值就行了
}
}
// 還沒有到達顯示松開刷新的時候,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();
}
}
// done狀態下
if (state == DONE) {
if (tempY - startY > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
}
}
// 更新headView的size
if (state == PULL_To_REFRESH) {
layout.setPadding(0, -1 * headContentHeight
+ (tempY - startY) / RATIO, 0, 0);
}
// 更新headView的paddingTop
if (state == RELEASE_To_REFRESH) {
layout.setPadding(0, (tempY - startY) / RATIO
- headContentHeight, 0, 0);
}
}
break;
}
}
return super.onTouchEvent(event);
}
private void onRefresh() {
if (refreshListener != null) {
refreshListener.onRefresh();
}
}
public interface OnRefreshListener {
public void onRefresh();
}
private void changeHeaderViewByState() {
switch (state) {
case RELEASE_To_REFRESH:
imageView_recommend_refresh.setVisibility(View.VISIBLE);
progressBar_recommend_refresh.setVisibility(View.GONE);
textView_recommend_new.setVisibility(View.VISIBLE);
textView_recommend_old.setVisibility(View.VISIBLE);
imageView_recommend_refresh.clearAnimation();
imageView_recommend_refresh.startAnimation(animation);
textView_recommend_new.setText("松開刷新");
break;
case PULL_To_REFRESH:
progressBar_recommend_refresh.setVisibility(View.GONE);
textView_recommend_new.setVisibility(View.VISIBLE);
textView_recommend_old.setVisibility(View.VISIBLE);
imageView_recommend_refresh.clearAnimation();
imageView_recommend_refresh.setVisibility(View.VISIBLE);
// 是由RELEASE_To_REFRESH狀態轉變來的
if (isBack) {
isBack = false;
imageView_recommend_refresh.clearAnimation();
imageView_recommend_refresh.startAnimation(reverseAnimation);
textView_recommend_new.setText("下拉刷新");
} else {
textView_recommend_new.setText("下拉刷新");
}
break;
case REFRESHING:
layout.setPadding(0, 0, 0, 0);
progressBar_recommend_refresh.setVisibility(View.VISIBLE);
imageView_recommend_refresh.clearAnimation();
imageView_recommend_refresh.setVisibility(View.GONE);
textView_recommend_new.setText("正在刷新...");
textView_recommend_old.setVisibility(View.VISIBLE);
break;
case DONE:
layout.setPadding(0, -1 * headContentHeight, 0, 0);
progressBar_recommend_refresh.setVisibility(View.GONE);
imageView_recommend_refresh.clearAnimation();
imageView_recommend_refresh.setImageResource(R.drawable.arrow);
textView_recommend_new.setText("下拉刷新");
textView_recommend_old.setVisibility(View.VISIBLE);
break;
}
}
public void setonRefreshListener(OnRefreshListener refreshListener) {
this.refreshListener = refreshListener;
isRefreshable = true;
}
public void onRefreshComplete() {
state = DONE;
textView_recommend_old.setText("最近更新:" + new Date().toLocaleString());
changeHeaderViewByState();
}
public void setAdapter(BaseAdapter adapter) {
textView_recommend_old.setText("最近更新:" + new Date().toLocaleString());
super.setAdapter(adapter);
}
//計算估計下拉刷新的所需要的寬高
private void measureView(View view) {
ViewGroup.LayoutParams p = view.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int viewWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int viewHeightSpec;
if (lpHeight > 0) {
viewHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
viewHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
view.measure(viewWidthSpec, viewHeightSpec);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
firstItemIndex = firstVisibleItem;
}
}
MyViewPager文件:
主要功能,重寫viewpager,為了避免listview和viewpager的焦點沖突。
package com.example.com.xiyouliwp.demo;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;
/**
* Created by lwp940118 on 2016/5/12.
* 李文朋
*/
public class MyViewPager extends ViewPager {
private ViewGroup parent;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attributeSet) {
super(context,attributeSet);
}
public void setNestedpParent(ViewGroup parent) {
this.parent = parent;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
return super.onInterceptTouchEvent(arg0);
}
@Override
public boolean onTouchEvent(MotionEvent arg0) {
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
return super.onTouchEvent(arg0);
}
}
MainActivity文件:
package com.example.com.xiyouliwp.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.com.xiyouliwp.demo.R;
public class MainActivity extends Activity {
private MyViewPager viewpager;
private List imageViews; // 滑動圖片的數組
private String[] titleStrings; // 滑動圖片的標題
private int[] imagevierid; // 滑動圖片的id;
private List views; // 滑動原點的view
private int currentItem = 0; // 當前圖片的索引號
private ScheduledExecutorService scheduledExecutorService;
private TextView textView_recommend_yuan;
private MyListView listView_recommend;
private ListView_Adapter list_adapter;
// 切換當前圖片
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 顯示當前圖片
viewpager.setCurrentItem(currentItem);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findid();
initViewpager();
initListview();
}
private void initViewpager() {
View header = LayoutInflater.from(MainActivity.this).inflate(
R.layout.myviewpager, null);
viewpager = (MyViewPager) header.
findViewById(R.id.viewpage_recommend);
imagevierid = new int[]{R.drawable.view1, R.drawable.view2, R.drawable.view3, R.drawable.viewtu
, R.drawable.view5};
titleStrings = new String[imagevierid.length];
titleStrings[0] = "寵物的再生聖地";
titleStrings[1] = "商店交易";
titleStrings[2] = "狗狗專屬衣物";
titleStrings[3] = "萌寵秀翻天";
titleStrings[4] = "寵物人性化培訓";
imageViews = new ArrayList();
//初始化圖片資源
for (int i = 0; i < imagevierid.length; i++) {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setBackgroundResource(imagevierid[i]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageViews.add(imageView);
}
textView_recommend_yuan = (TextView) header.findViewById(R.id.textview_Viewpager);
//初始化原點
views = new ArrayList();
views.add(header.findViewById(R.id.view_recommend_yuan1));
views.add(header.findViewById(R.id.view_recommend_yuan2));
views.add(header.findViewById(R.id.view_recommend_yuan3));
views.add(header.findViewById(R.id.view_recommend_yuan4));
views.add(header.findViewById(R.id.view_recommend_yuan5));
textView_recommend_yuan.setText(titleStrings[0]);
viewpager.setNestedpParent((ViewGroup) viewpager.getParent());
//Viewpager的adapter
// viewPager_recommend.setAdapter(new viewpagerecommendAdapter(getActivity()));
viewpagerecommendAdapter adapter = new viewpagerecommendAdapter(MainActivity.this);
viewpager.setAdapter(adapter);
viewpager.setOnPageChangeListener(new viewpagerRecommendPageChangeListener());
listView_recommend.addHeaderView(header);
}
//viewpagger的PageChangeListener
private class viewpagerRecommendPageChangeListener implements ViewPager.OnPageChangeListener {
private int oldposition = 0;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
currentItem = position;
textView_recommend_yuan.setText(titleStrings[position]);
views.get(oldposition).setBackgroundResource(R.drawable.dot_normal);
views.get(position).setBackgroundResource(R.drawable.dot_focused);
oldposition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
//viewpager的aderpter
private class viewpagerecommendAdapter extends PagerAdapter {
private Context mContext;
public viewpagerecommendAdapter(Context mContext) {
this.mContext = mContext;
}
@Override
public int getCount() {
return imagevierid.length;
}
@Override
public Object instantiateItem(View container, int position) {
((ViewPager) container).addView(imageViews.get(position));
return imageViews.get(position);
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public void finishUpdate(View arg0) {
}
}
public class ListView_Adapter extends BaseAdapter {
private List userInfos; // 標題
private LayoutInflater layoutInflater = null;
public ListView_Adapter( List strings) {
this.userInfos = strings;
layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return userInfos.size();
}
@Override
public Object getItem(int position) {
return userInfos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_mylistview,
null);
holder.textview = (TextView)convertView. findViewById(R.id.textview);
// 對item中的控件的id進行尋找
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.textview.setText(userInfos.get(position));
}
return convertView;
}
class ViewHolder {
TextView textview;
}
}
private void initListview() {
list_adapter = new ListView_Adapter( getArrylst());
listView_recommend.setAdapter(list_adapter);
listView_recommend
.setonRefreshListener(new MyListView.OnRefreshListener() {
@Override
public void onRefresh() {
new AsyncTask() {
protected Void doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
list_adapter.notifyDataSetChanged();
listView_recommend.onRefreshComplete();
}
}.execute();
}
});
}
// listview的數據入口
private List getArrylst() {
List titleArray = new ArrayList();
for (int i = 0; i < 50; i++) {
titleArray.add("dome數據" + i);
}
return titleArray;
}
@Override
public void onStart() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new YuanDianRun(), 1, 2,
TimeUnit.SECONDS);
super.onStart();
}
@Override
public void onStop() {
scheduledExecutorService.shutdown();
super.onStop();
}
private class YuanDianRun implements Runnable {
@Override
public void run() {
synchronized (viewpager) {
currentItem = (currentItem + 1) % imageViews.size();
// handler切換圖片
handler.obtainMessage().sendToTarget();
}
}
}
// 尋找ID
private void findid() {
listView_recommend = (MyListView) findViewById(R.id.listview_recommend);
}
}
布局文件分別如下:
activity_main文件主要實現主界面的布局
item_mylistview文件主要實現listview的item的布局
mylistview_shuaxin文件主要實現下拉刷新時的布局
<framelayout android:background="#ddf0ed" android:layout_alignparentleft="true" android:layout_centervertical="true" android:layout_height="wrap_content" android:layout_width="wrap_content">
</framelayout>
myviewpager文件的布局實現廣告欄的布局
<framelayout android:layout_height="150dp" android:layout_width="match_parent">
</framelayout>
還有drawable文件中的一些XML
dot_focused.xml和dot_normal.xml實現廣告滑動上面的五個小圓點
圓點的style文件如下:
還有上面布局文件中的color文件中的顏色代碼:
#00000000
OK當你看完這些時,你已經成功實現了listview的下拉刷新和listview嵌套viewpager仿淘寶搜狐的廣告主頁面。
效果圖:右邊的文字欄上下移動,沒有文字會自動停止移動。這和之前我寫的紋理移動不同,之前的是循環移動,這次是定位移動。頂點著色器: uniform mat4 uM
1、概述隨著Material Design的逐漸的普及,業內也有很多具有分享精神的伙伴翻譯了material design specification,中文翻譯地址:Ma
說來慚愧,MVP的架構模式已經在Android領域出現一兩年了,但是到今天自己才開始Android領域中的MVP架構征程。閒話不多說,開始吧!一、架構演變概述我記得我找
仿微信通訊錄右側快速定位字母表控件先看效果圖: 界面比較單調,湊合看,主要看功能。這種控件在很多應用的通訊錄的界面,MIUI裡面的通訊錄都有這個功能,其實這是一