码迷,mamicode.com
首页 > 其他好文 > 详细

侧滑2

时间:2016-02-16 11:44:52      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:

如下图是侧滑的效果图

           技术分享                   技术分享

 

实现的功能主要是用ViewDragHelper,用ViewDragHelper来自定义一个侧滑面板来实现侧滑

如下是自定义的侧滑面板

  1 package com.demo.sb.widget;
  2 
  3 import com.nineoldandroids.view.ViewHelper;
  4 
  5 import android.content.Context;
  6 import android.graphics.Color;
  7 import android.graphics.PorterDuff.Mode;
  8 import android.support.v4.view.ViewCompat;
  9 import android.support.v4.widget.ViewDragHelper;
 10 import android.util.AttributeSet;
 11 import android.util.Log;
 12 import android.view.MotionEvent;
 13 import android.view.View;
 14 import android.view.ViewGroup;
 15 import android.widget.FrameLayout;
 16 
 17 /**
 18  * 侧滑面板
 19  * 
 20  * @author Administrator
 21  * 
 22  */
 23 public class DragLayout extends FrameLayout {
 24 
 25     private ViewDragHelper mDragHelper;
 26     private ViewGroup mLeftContent;
 27     private ViewGroup mMainContent;
 28 
 29     private Status mStatus = Status.Close;
 30     private OnDragStatusChangeListener mListener;
 31 
 32     /**
 33      * 状态枚举
 34      */
 35     public static enum Status {
 36         Close, Open, Draging;
 37     }
 38 
 39     public interface OnDragStatusChangeListener {
 40         void onClose();
 41 
 42         void onOpen();
 43 
 44         void onDraging(float percent);
 45     }
 46 
 47     public Status getStatus() {
 48         return mStatus;
 49     }
 50 
 51     public void setStatus(Status mStatus) {
 52         this.mStatus = mStatus;
 53     }
 54 
 55     public void setDragStatusListener(OnDragStatusChangeListener mListener) {
 56         this.mListener = mListener;
 57     }
 58 
 59     public DragLayout(Context context) {
 60         this(context, null);
 61         // TODO Auto-generated constructor stub
 62     }
 63 
 64     public DragLayout(Context context, AttributeSet attrs) {
 65         this(context, attrs, 0);
 66         // TODO Auto-generated constructor stub
 67     }
 68 
 69     public DragLayout(Context context, AttributeSet attrs, int defStyle) {
 70         super(context, attrs, defStyle);
 71         // TODO Auto-generated constructor stub
 72         /**
 73          * a . 初始化(通过静态的方法)
 74          */
 75         mDragHelper = ViewDragHelper.create(this, mCallback);
 76     }
 77 
 78     /**
 79      * c. 重写Callback的事件
 80      */
 81     ViewDragHelper.Callback mCallback = new ViewDragHelper.Callback() {
 82         /**
 83          * 1. 根据返回结果决定当前的child是否可以拖拽 child 当前被拖拽的View pointerId 区分多点触摸的id
 84          */
 85         @Override
 86         public boolean tryCaptureView(View child, int pointerId) {
 87             Log.d("jiejie", "tryCaptureView: " + child);
 88             return true;// 都可以尝试被拖拽
 89             // return child == mMainContent;//只有主程序的View可以被拖拽
 90         }
 91 
 92         public void onViewCaptured(View capturedChild, int activePointerId) {
 93             // 当capturedChild被捕获时,调用
 94             Log.d("jiejie", "onViewCaptured: " + capturedChild);
 95         }
 96 
 97         public int getViewHorizontalDragRange(View child) {
 98             // 返回拖拽的范围,不对拖拽进行真正的限制。仅仅决定了动画的执行速度
 99             return mRange;
100         }
101 
102         /**
103          * 2. 根据建议值 修正将要移动到的(横向)位置(重要) 此时还没有真正移动
104          */
105         public int clampViewPositionHorizontal(View child, int left, int dx) {
106             Log.d("jiejie", "clampViewPositionHorizontal: " + left);
107             if (child == mMainContent) {
108                 left = fixLeft(left);
109             }
110             return left;
111         }
112 
113         /**
114          * 3. 当View位置改变的时候,处理要做的事情(更新状态, 伴随动画, 重绘界面) 此时,View已经发生了位置的改变
115          * changedView 改变位置的View left 新的左边值 dx 水平方向变化量
116          */
117         public void onViewPositionChanged(View changedView, int left, int top,
118                 int dx, int dy) {
119             super.onViewPositionChanged(changedView, left, top, dx, dy);
120             Log.d("jiejie", "onViewPositionChanged: " + "left:" + left
121                     + " dx: " + dx);
122             int newLeft = left;
123             if (changedView == mLeftContent) {
124                 // 把当前变化量专递给mMainContent
125                 newLeft = mMainContent.getLeft() + dx;
126             }
127             // 进行修正
128             newLeft = fixLeft(newLeft);
129 
130             if (changedView == mLeftContent) {
131                 // 当左面板移动之后,再强制放回去
132                 mLeftContent.layout(0, 0, 0 + mWidth, 0 + mHeight);
133                 mMainContent.layout(newLeft, 0, newLeft + mWidth, 0 + mHeight);
134             }
135 
136             /**
137              * 更新状态时设置动画(也可以不设置,不设置的话则默认平滑的状态,也可以省很多代码) 设置左面板和主面板,背景的动画
138              */
139             dispatchDragEvent(newLeft);
140 
141             // 为了兼容低版本,每次修改值之后,进行重绘
142             invalidate();
143         }
144 
145         /**
146          * 4. 当View被释放的时候,处理的事情(执行动画) View releasedChild 被释放的子View float xvel
147          * 水平方向的速度,向右为正 float yvel 竖直方向的速度, 向下为正
148          */
149         public void onViewReleased(View releasedChild, float xvel, float yvel) {
150             Log.d("jiejie", "onViewReleased: " + "xvel: " + xvel + "yvel: "
151                     + yvel);
152             super.onViewReleased(releasedChild, xvel, yvel);
153             // 判断执行 关闭/开启
154             // 先考虑所有开启的情况,剩下的就是都是关闭的情况
155             if (xvel == 0 && mMainContent.getLeft() > (mRange / 2.0f)) {
156                 open();
157             } else if (xvel > 0) {
158                 open();
159             } else {
160                 chose();
161             }
162         }
163 
164         public void onViewDragStateChanged(int state) {
165             super.onViewDragStateChanged(state);
166         }
167     };
168 
169     /**
170      * 根据范围修正左边值
171      * 
172      * @param left
173      * @return
174      */
175     private int fixLeft(int left) {
176         if (left < 0) {
177             return 0;
178         } else if (left > mRange) {
179             return mRange;
180         }
181         return left;
182     }
183 
184     /**
185      * 执行动画
186      * 
187      * @param newLeft
188      */
189     protected void dispatchDragEvent(int newLeft) {
190         // TODO Auto-generated method stub
191         float percent = newLeft * 1.0f / mRange;
192         Log.d("jiejie", "percent: " + percent);
193         if (mListener != null) {
194             mListener.onDraging(percent);
195         }
196 
197         // 更新状态,执行回调
198         Status preStatus = mStatus;
199         mStatus = updateStatus(percent);
200 
201         if (mStatus != preStatus) {
202             // 状态发生变化
203             if (mStatus == Status.Close) {
204                 // 当前变为关闭状态
205                 if (mListener != null) {
206                     mListener.onClose();
207                 }
208             } else if (mStatus == Status.Open) {
209                 if (mListener != null) {
210                     mListener.onOpen();
211                 }
212             }
213         }
214 
215         // 伴随动画
216         animViews(percent);
217     }
218 
219     private Status updateStatus(float percent) {
220         if (percent == 0f) {
221             return Status.Close;
222         } else if (percent == 1.0f) {
223             return Status.Open;
224         }
225         return Status.Draging;
226     }
227 
228     private void animViews(float percent) {
229         // TODO Auto-generated method stub
230         /**
231          * >1.左面板:缩放动画,平移动画,透明度动画 缩放动画0.0 - > 1.0 >> 0.5f -> 1.0f >>>
232          * 0.5f*percent+0.5f mLeftContent.setScaleX(0.5f + 0.5f * percent);
233          * mLeftContent.setScaleY(0.5f + 0.5f * percent);
234          */
235         // mLeftContent.setScaleY(0.5f + 0.5f * percent);
236         // mLeftContent.setScaleX(0.5f + 0.5f * percent);
237         ViewHelper.setScaleX(mLeftContent, evaluate(percent, 0.5f, 1.0f));
238         ViewHelper.setScaleY(mLeftContent, 0.5f + 0.5f * percent);
239         // 平移动画:-mWidth / 2.0 f - > 0.0f
240         ViewHelper.setTranslationX(mLeftContent,
241                 evaluate(percent, -mWidth / 2.0f, 0));
242         // 透明度: 0.5 -> 1.0f
243         ViewHelper.setAlpha(mLeftContent, evaluate(percent, 0.5f, 1.0f));
244 
245         /**
246          * >2. 主面板:缩放动画
247          */
248         // 1.0f -> 0.8f
249         ViewHelper.setScaleX(mMainContent, evaluate(percent, 1.0f, 0.8f));
250         ViewHelper.setScaleY(mMainContent, evaluate(percent, 1.0f, 0.8f));
251 
252         /**
253          * >3. 背景动画: 亮度变化(颜色变化)
254          */
255         getBackground()
256                 .setColorFilter(
257                         (Integer) evaluateColor(percent, Color.BLACK,
258                                 Color.TRANSPARENT), Mode.SRC_OVER);
259     }
260 
261     /**
262      * 估值器
263      * 
264      * @param fraction
265      * @param startValue
266      * @param endValue
267      * @return
268      */
269     public Float evaluate(float fraction, Number startValue, Number endValue) {
270         float startFloat = startValue.floatValue();
271         return startFloat + fraction * (endValue.floatValue() - startFloat);
272     }
273 
274     /**
275      * 颜色变化过度
276      * 
277      * @param fraction
278      * @param startValue
279      * @param endValue
280      * @return
281      */
282     public Object evaluateColor(float fraction, Object startValue,
283             Object endValue) {
284         int startInt = (Integer) startValue;
285         int startA = (startInt >> 24) & 0xff;
286         int startR = (startInt >> 16) & 0xff;
287         int startG = (startInt >> 8) & 0xff;
288         int startB = startInt & 0xff;
289 
290         int endInt = (Integer) endValue;
291         int endA = (endInt >> 24) & 0xff;
292         int endR = (endInt >> 16) & 0xff;
293         int endG = (endInt >> 8) & 0xff;
294         int endB = endInt & 0xff;
295 
296         return (int) ((startA + (int) (fraction * (endA - startA))) << 24)
297                 | (int) ((startR + (int) (fraction * (endR - startR))) << 16)
298                 | (int) ((startG + (int) (fraction * (endG - startG))) << 8)
299                 | (int) ((startB + (int) (fraction * (endB - startB))));
300     }
301 
302     @Override
303     public void computeScroll() {
304         // TODO Auto-generated method stub
305         super.computeScroll();
306         // 2. 持续平滑动画(高频率调用)
307         if (mDragHelper.continueSettling(true)) {
308             // 如果返回true,动画还需要继续执行
309             ViewCompat.postInvalidateOnAnimation(this);
310         }
311     }
312 
313     // public void chose() {
314     // // TODO Auto-generated method stub
315     // chose(true);
316     // }
317     public void chose() {
318         // TODO Auto-generated method stub
319         chose(true);
320     }
321 
322     /**
323      * 关闭
324      * 
325      * @param b
326      */
327     public void chose(boolean isSmooth) {
328         // TODO Auto-generated method stub
329         int finalLeft = 0;
330         // 1. 触发一个平滑动画
331         if (isSmooth) {
332             if (mDragHelper.smoothSlideViewTo(mMainContent, finalLeft, 0)) {
333                 // 返回true代表还没有移动到指定位置,需要刷新界面
334                 // 参数传this(child所在的ViewGroup)
335                 ViewCompat.postInvalidateOnAnimation(this);
336             }
337         } else {
338             mMainContent.layout(finalLeft, 0, finalLeft + mWidth, 0 + mHeight);
339         }
340     }
341 
342     public void open() {
343         // TODO Auto-generated method stub
344         open(true);
345     }
346 
347     /**
348      * 开启
349      * 
350      * @param b
351      */
352     public void open(boolean isSmooth) {
353         // TODO Auto-generated method stub
354         int finalLeft = mRange;
355         if (isSmooth) {
356             // 1. 触发一个平滑动画
357             if (mDragHelper.smoothSlideViewTo(mMainContent, finalLeft, 0)) {
358                 // 返回true代表还没有移动到指定位置,需要刷新界面
359                 // 参数this(child所在的ViewGroup)
360                 ViewCompat.postInvalidateOnAnimation(this);
361             }
362         } else {
363             mMainContent.layout(finalLeft, 0, finalLeft + mWidth, 0 + mHeight);
364         }
365     }
366 
367     /**
368      * b. 专递触摸事件
369      */
370     public boolean onInterceptTouchEvent(MotionEvent ev) {
371         // 传递给mDragHandler
372         return mDragHelper.shouldInterceptTouchEvent(ev);
373     };
374 
375     @Override
376     public boolean onTouchEvent(MotionEvent event) {
377         // TODO Auto-generated method stub
378         try {
379             mDragHelper.processTouchEvent(event);
380         } catch (Exception e) {
381             e.printStackTrace();
382         }
383         // 返回true,持续接收事件
384         return true;
385     }
386 
387     /**
388      * 当View中所有的子控件 均被映射成xml后触发
389      */
390     @Override
391     protected void onFinishInflate() {
392         // TODO Auto-generated method stub
393         super.onFinishInflate();
394         if (getChildCount() < 2) {
395             throw new IllegalAccessError(
396                     "布局至少有2个孩子. Your ViewGroup must have 2 children at least");
397         }
398         if (!(getChildAt(0) instanceof ViewGroup && getChildAt(1) instanceof ViewGroup)) {
399             throw new IllegalArgumentException(
400                     "子View必须是ViewGroup的子类. Your children must be an instance of ViewGroup");
401         }
402         mLeftContent = (ViewGroup) getChildAt(0);
403         mMainContent = (ViewGroup) getChildAt(1);
404     }
405 
406     /**
407      * 当view的大小发生变化时触发
408      */
409     private int mRange;
410     private int mHeight;
411     private int mWidth;
412 
413     @Override
414     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
415         // 当尺寸有变化的时候调用
416         super.onSizeChanged(w, h, oldw, oldh);
417         mHeight = getMeasuredHeight();
418         mWidth = getMeasuredWidth();
419         mRange = (int) (mWidth * 0.6f);
420     }
421 
422 }

如下是主程序代码

  1 package com.demo.sb.main;
  2 
  3 import com.demo.sb.mainfram.TentcentOneFragment;
  4 import com.demo.sb.mainfram.TentcentThreeFragment;
  5 import com.demo.sb.mainfram.TentcentTwoFragment;
  6 import com.demo.sb.utils.Utils;
  7 import com.demo.sb.widget.DragLayout;
  8 import com.demo.sb.widget.DragLayout.OnDragStatusChangeListener;
  9 import com.demo.sb.widget.MyListLinearLayout;
 10 import com.demo.suibian.R;
 11 import com.nineoldandroids.animation.ObjectAnimator;
 12 import com.nineoldandroids.view.ViewHelper;
 13 
 14 import android.os.Bundle;
 15 import android.support.v4.app.FragmentActivity;
 16 import android.support.v4.app.FragmentManager;
 17 import android.support.v4.app.FragmentTransaction;
 18 import android.view.View;
 19 import android.view.Window;
 20 import android.view.animation.CycleInterpolator;
 21 import android.widget.ImageView;
 22 import android.widget.RadioGroup;
 23 import android.widget.RadioGroup.OnCheckedChangeListener;
 24 import android.widget.TextView;
 25 
 26 /**
 27  * 侧滑菜单
 28  * 
 29  * @author Administrator
 30  * 
 31  */
 32 public class Activity_Tencent extends FragmentActivity {
 33 
 34     private RadioGroup rg_tencent_mian;
 35     // private FrameLayout fl_tencent_content;
 36     private ImageView iv_header;
 37     private TextView tv_header;
 38 
 39     private TentcentOneFragment oneFragment;
 40     private TentcentTwoFragment twoFragment;
 41     private TentcentThreeFragment threeFragment;
 42     private static DragLayout mDragLayout;
 43 
 44     @Override
 45     protected void onCreate(Bundle savedInstanceState) {
 46         // TODO Auto-generated method stub
 47         super.onCreate(savedInstanceState);
 48         requestWindowFeature(Window.FEATURE_NO_TITLE);
 49         setContentView(R.layout.activity_tencent);
 50 
 51         initView();
 52         initData();
 53 
 54     }
 55 
 56     private void initView() {
 57         // TODO Auto-generated method stub
 58         rg_tencent_mian = (RadioGroup) findViewById(R.id.rg_tencent_mian);
 59         iv_header = (ImageView) findViewById(R.id.iv_header);
 60         tv_header = (TextView) findViewById(R.id.tv_header);
 61         MyListLinearLayout mLayout = (MyListLinearLayout) findViewById(R.id.mll);
 62         mDragLayout = (DragLayout) findViewById(R.id.dl);
 63         // 设置引用
 64         mLayout.setDraglayout(mDragLayout);
 65 
 66         mDragLayout.setDragStatusListener(new OnDragStatusChangeListener() {
 67 
 68             @Override
 69             public void onOpen() {
 70                 // TODO Auto-generated method stub
 71                 Utils.showToast(Activity_Tencent.this, "onOpen");
 72             }
 73 
 74             @Override
 75             public void onDraging(float percent) {
 76                 // TODO Auto-generated method stub
 77                 // 跟新图标的透明度
 78                 // 1.0 -> 0.0
 79                 ViewHelper.setAlpha(iv_header, 1 - percent);
 80             }
 81 
 82             @Override
 83             public void onClose() {
 84                 // TODO Auto-generated method stub
 85                 Utils.showToast(Activity_Tencent.this, "onClose");
 86                 // 让图片开会晃动
 87                 ObjectAnimator mAnim = ObjectAnimator.ofFloat(iv_header,
 88                         "translationX", 15.0f);
 89                 mAnim.setInterpolator(new CycleInterpolator(4));
 90                 mAnim.setDuration(500);
 91                 mAnim.start();
 92             }
 93         });
 94 
 95         iv_header.setOnClickListener(new View.OnClickListener() {
 96 
 97             @Override
 98             public void onClick(View arg0) {
 99                 // TODO Auto-generated method stub
100                 mDragLayout.open(true);
101             }
102         });
103     }
104 
105     private void initData() {
106         // TODO Auto-generated method stub
107         rg_tencent_mian.check(R.id.rb_tencent_one);
108 
109         oneFragment = new TentcentOneFragment();
110         twoFragment = new TentcentTwoFragment();
111         threeFragment = new TentcentThreeFragment();
112         // 获取fragment管理器
113         FragmentManager fragmentManager = getSupportFragmentManager();
114         // 打开事务
115         FragmentTransaction transaction = fragmentManager.beginTransaction();
116         // 把内容显示到帧布局中
117         transaction.add(R.id.fl_tencent_content, oneFragment);
118         transaction.add(R.id.fl_tencent_content, twoFragment);
119         transaction.add(R.id.fl_tencent_content, threeFragment);
120         transaction.show(oneFragment).hide(twoFragment).hide(threeFragment);
121         // 提交
122         transaction.commit();
123         tv_header.setText("head");
124 
125         rg_tencent_mian
126                 .setOnCheckedChangeListener(new OnCheckedChangeListener() {
127 
128                     @Override
129                     public void onCheckedChanged(RadioGroup arg0, int arg1) {
130                         // TODO Auto-generated method stub
131                         switch (arg1) {
132                         case R.id.rb_tencent_one:
133                             tv_header.setText("head");
134                             getSupportFragmentManager().beginTransaction()
135                                     .show(oneFragment).hide(twoFragment)
136                                     .hide(threeFragment).commit();
137                             break;
138                         case R.id.rb_tencent_two:
139                             tv_header.setText("联系人");
140                             getSupportFragmentManager().beginTransaction()
141                                     .show(twoFragment).hide(oneFragment)
142                                     .hide(threeFragment).commit();
143                             break;
144                         case R.id.rb_tencent_three:
145                             tv_header.setText("动态");
146                             getSupportFragmentManager().beginTransaction()
147                                     .show(threeFragment).hide(oneFragment)
148                                     .hide(twoFragment).commit();
149                             break;
150                         default:
151                             break;
152                         }
153                     }
154                 });
155     }
156 
157 }

主程序的布局xml为

技术分享
<?xml version="1.0" encoding="utf-8"?>
<com.demo.sb.widget.DragLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#50ff"
        android:orientation="vertical"
        android:paddingBottom="50dp"
        android:paddingLeft="10dp"
        android:paddingRight="50dp"
        android:paddingTop="50dp" >

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:contentDescription="@null"
            android:src="@drawable/head" />
    </LinearLayout>

    <com.demo.sb.widget.MyListLinearLayout
        android:id="@+id/mll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#18B6EF"
            android:gravity="center_vertical" >

            <ImageView
                android:id="@+id/iv_header"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginLeft="15dp"
                android:contentDescription="@null"
                android:src="@drawable/head" />

            <TextView
                android:id="@+id/tv_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_centerHorizontal="true"
                android:textColor="#fff"
                android:textSize="18sp"
                android:text="" />
        </RelativeLayout>

        <FrameLayout
            android:id="@+id/fl_tencent_content"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <RadioGroup
            android:id="@+id/rg_tencent_mian"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bottom_tab_bg"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/rb_tencent_one"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:button="@null"
                android:drawablePadding="3dp"
                android:drawableTop="@drawable/btn_tab_home_selector"
                android:gravity="center"
                android:text="消息"
                android:textColor="@drawable/btn_tab_text_selector" />

            <RadioButton
                android:id="@+id/rb_tencent_two"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:button="@null"
                android:drawablePadding="3dp"
                android:drawableTop="@drawable/btn_tab_home_selector"
                android:gravity="center"
                android:text="联系人"
                android:textColor="@drawable/btn_tab_text_selector" />

            <RadioButton
                android:id="@+id/rb_tencent_three"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:button="@null"
                android:drawablePadding="3dp"
                android:drawableTop="@drawable/btn_tab_home_selector"
                android:gravity="center"
                android:text="动态"
                android:textColor="@drawable/btn_tab_text_selector" />
        </RadioGroup>
    </com.demo.sb.widget.MyListLinearLayout>

</com.demo.sb.widget.DragLayout>
View Code

主界面是用继承的FragmentActivity来实现下面3个按钮的点击事件,其中第一个Fragment(TentcentOneFragment)内只有个ListView

当停在侧滑界面时,ListView不能进行上下滑动

TentcentOneFragment的代码和xml布局

技术分享
package com.demo.sb.mainfram;

import com.demo.suibian.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class TentcentOneFragment extends Fragment {

    private ListView mListView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.tentcentonefragment, null, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        mListView = (ListView) getActivity().findViewById(R.id.lv_one_listview);
        mListView.setAdapter(new MyListAdapter());
    }

    private int[] con = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
    private String[] name = { "第一人", "第二人", "第三人", "第四人", "第五人", "第六人", "第七人",
            "第八人", "第九人", "第十人", "第十一人", "第十二人", "第十三人" };

    private class MyListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return name.length;
        }

        @Override
        public String getItem(int arg0) {
            // TODO Auto-generated method stub
            return name[arg0];
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            ViewHolder holder;
            if (arg1 == null) {
                arg1 = View.inflate(getActivity(), R.layout.item_onelist, null);
                holder = new ViewHolder();
                holder.tv_name = (TextView) arg1.findViewById(R.id.item_name);
                holder.tv_fight = (TextView) arg1.findViewById(R.id.item_fight);
                arg1.setTag(holder);
            } else {
                holder = (ViewHolder) arg1.getTag();
            }
            holder.tv_name.setText("名字:" + getItem(arg0));
            holder.tv_fight.setText("战斗力:" + con[arg0]);
            return arg1;
        }

    }

    static class ViewHolder {
        TextView tv_name;
        TextView tv_fight;
    }
}
View Code
技术分享
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/lv_one_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
View Code

第二个Fragment(TentcentTwoFragment)内只有个ViewPager可以进行左右滑动不过还是有点问题

技术分享
package com.demo.sb.mainfram;

import java.util.ArrayList;
import com.demo.suibian.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class TentcentTwoFragment extends Fragment {

    private LinearLayout ll_two_group;// 引导圆点的父控件
    private ViewPager mViewPager;
    private ImageView[] diandian;//ViewPager上的点点
    private static final int[] mImageIds = new int[] { R.drawable.c,
            R.drawable.a, R.drawable.d };
    private ArrayList<ImageView> mImageViewList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.tentcenttwofragment, null, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        // TODO Auto-generated method stub
        mViewPager = (ViewPager) getActivity().findViewById(
                R.id.vp_tentwo_viewpager);
        ll_two_group = (LinearLayout) getActivity().findViewById(
                R.id.ll_two_group);
        initViewPager();
        mViewPager.setAdapter(new GuideAdapter());
        mViewPager.setCurrentItem(0);
        mViewPager.setOnPageChangeListener(new GuidePagerListener());
    }

    private void initViewPager() {
        // TODO Auto-generated method stub
        // 初始化引导的3个界面
        mImageViewList = new ArrayList<ImageView>();
        for (int i = 0; i < mImageIds.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(mImageIds[i]);
            mImageViewList.add(imageView);
        }
        
        diandian = new ImageView[mImageIds.length];
        for (int i = 0; i < mImageIds.length; i++) {
            //循环加入点点图片组
            diandian[i] = new ImageView(getActivity());
            if( i== 0){
                diandian[i].setImageResource(R.drawable.point_selecte);
            }else {
                diandian[i].setImageResource(R.drawable.point_normal);
            }
            diandian[i].setPadding(8, 8, 8, 8);
            ll_two_group.addView(diandian[i]);
        }
//        // 初始化引导页的小圆点
//        for (int i = 0; i < mImageIds.length; i++) {
//            View point = new View(getActivity());
//            point.setBackgroundResource(R.drawable.point_normal);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                    10, 10);
//            if (i > 0) {
//                params.leftMargin = 10;// 设置圆点的间隔
//            }
//            point.setLayoutParams(params);// 设置圆点的大小
//            ll_two_group.addView(point);
//        }
//        
    }

    class GuideAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mImageIds.length;
            //return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            container.addView(mImageViewList.get(position));
            return mImageViewList.get(position);
//            container.addView(mImageViewList.get(position%mImageViewList.size()));
//            return mImageViewList.get(position%mImageViewList.size());
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView((View) object);
            //container.removeView(mImageViewList.get(position%mImageViewList.size()));
        }
    }

    /**
     * ViewPager 的滑动监听
     * 
     * @author Administrator
     * 
     */
    class GuidePagerListener implements OnPageChangeListener {
        // 操作屏幕时发生变化
        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }

        // 屏幕滚动过程中不断被调用
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
//            int len = (int) (mPointWidth * arg1) + arg0 * mPointWidth;
//            System.out.println(len);
//            // 获取当前红色点的布局参数
//            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view_two_point
//                    .getLayoutParams();
//            params.leftMargin = len;// 设置左边距
//            view_two_point.setLayoutParams(params);// 重新给小红点设置布局参数
        }

        // 哪个页面被选中 position就是当前滑动到的页面
        @Override
        public void onPageSelected(int position) {
            // TODO Auto-generated method stub
            System.out.println("第几个页面" + position  +"   "+ position%mImageViewList.size());
            for (int i = 0; i < mImageIds.length; i++) {
                diandian[position].setImageResource(R.drawable.point_selecte);
                if(i != position){
                    diandian[i].setImageResource(R.drawable.point_normal);
                }
            }
        }
    }
}
View Code
技术分享
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:background="#0f0"
 6     android:orientation="vertical" >
 7 
 8     <TextView
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:text="@string/app_name" />
12 
13     <RelativeLayout
14         android:layout_width="match_parent"
15         android:layout_height="200dp" >
16 
17         <com.demo.sb.widget.MyViewPager
18             android:id="@+id/vp_tentwo_viewpager"
19             android:layout_width="match_parent"
20             android:layout_height="match_parent" />
21 
22         <RelativeLayout
23             android:layout_width="wrap_content"
24             android:layout_height="wrap_content"
25             android:layout_alignParentBottom="true"
26             android:layout_centerHorizontal="true"
27             android:layout_marginBottom="25dp" >
28 
29             <LinearLayout
30                 android:id="@+id/ll_two_group"
31                 android:layout_width="wrap_content"
32                 android:layout_height="wrap_content"
33                 android:orientation="horizontal" />            
34         </RelativeLayout>
35     </RelativeLayout>
36 
37     <TextView
38         android:layout_width="match_parent"
39         android:layout_height="wrap_content"
40         android:text="@string/app_name" />
41 
42 </LinearLayout>
View Code

下面是2个工具类

第一个是自定义的线性布局可以当侧滑界面打开时,让ListView不能进行滑动

技术分享
 1 package com.demo.sb.widget;
 2 
 3 import com.demo.sb.widget.DragLayout.Status;
 4 
 5 import android.content.Context;
 6 import android.util.AttributeSet;
 7 import android.view.MotionEvent;
 8 import android.widget.LinearLayout;
 9 
10 public class MyListLinearLayout extends LinearLayout {
11     
12     private DragLayout mDragLayout;
13     public MyListLinearLayout(Context context) {
14         super(context);
15         // TODO Auto-generated constructor stub
16     }
17 
18     public MyListLinearLayout(Context context, AttributeSet attrs) {
19         super(context, attrs);
20         // TODO Auto-generated constructor stub
21     }
22 
23 //    public MyListLinearLayout(Context context, AttributeSet attrs, int defStyle) {
24 //        super(context, attrs, defStyle);
25 //        // TODO Auto-generated constructor stub
26 //    }
27     
28     public void setDraglayout(DragLayout mDragLayout){
29         this.mDragLayout = mDragLayout;
30     }
31     
32     @Override
33     public boolean onInterceptTouchEvent(MotionEvent ev) {
34         // TODO Auto-generated method stub
35         if(mDragLayout.getStatus() == Status.Close){
36             return super.onInterceptTouchEvent(ev);
37             
38         }else {
39             return true;
40         }
41     }
42     
43     @Override
44     public boolean onTouchEvent(MotionEvent event) {
45         // TODO Auto-generated method stub
46         if(mDragLayout.getStatus() == Status.Close){
47             return super.onTouchEvent(event);
48             
49         }else {
50             if(event.getAction() == MotionEvent.ACTION_UP){
51                 mDragLayout.chose();;
52             }
53             return true;
54         }
55     }
56 }
View Code

第二个是dp和px 的转化还有自定义Toast的设置比较常用

 1 package com.demo.sb.utils;
 2 
 3 import android.content.Context;
 4 import android.widget.Toast;
 5 
 6 public class DensityUtil {
 7     
 8     /**
 9      * 根据手机的分辨率从dip的单位转为px(像素)
10      */
11     public static int dip2px(Context context, float dp) {
12         float density = context.getResources().getDisplayMetrics().density;
13         int px = (int) (dp * density + 0.5f);// 4.9->5 4.4->4
14         return px;
15     }
16     /**
17      * 根据手机的分辨率从px(像素)的单位转化成dip
18      * @param ctx
19      * @param px
20      * @return
21      */
22     public static float px2dip(Context ctx, int px) {
23         float density = ctx.getResources().getDisplayMetrics().density;
24         float dp = px / (density + 0.5f);
25 
26         return dp;
27     }
28     
29     /**
30      * 自定义吐司
31      * 
32      */
33     public static Toast mToast;
34     public static void showToast(Context mContext, String msg) {
35         if (mToast == null) {
36             mToast = Toast.makeText(mContext, "", Toast.LENGTH_SHORT);
37         }
38         mToast.setText(msg);
39         mToast.show();
40     }
41 }

 

侧滑2

标签:

原文地址:http://www.cnblogs.com/wangfengdange/p/5192071.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!