新闻阅读器频道管理
原文链接:http://blog.csdn.net/vipzjyno1/article/details/25005851
本例子实现的功能是很多新闻阅读器(网易,今日头条,360新闻等)以及腾讯视频等里面都会出现的频道管理功能,点击可以增删频道,长按拖拽排序。下面的效果图没有拖拽的时候的移动动画,DEMO里面有,可以下载看看
实现思路:
获取数据库中频道的列表,如果为空,赋予默认列表,并存入数据库,之后通过对应的适配器赋给对应的GridView
2个GridView–(1.DragGrid 2. OtherGridView)
DragGrid 用于显示我的频道,带有长按拖拽效果
OtherGridView用于显示更多频道,不带推拽效果
注:由于屏幕大小不一定,外层使用ScrollView,所以2者都要重写计算高度点击2个GridView的时候,根据点击的Item对应的position,获取position对应的view,进行创建一层移动的动画层
起始位置:点击的positiongetLocationInWindow()获取。终点位置:另一个GridView的最后个ITEM 的position + 1的位置。
并赋予移动动画,等动画结束后对2者对应的频道列表进行数据的remove和add操作。设置点击和拖动的限制条件,如 推荐 这个ITEM是不允许用户操作的。
拖动的DragGrid的操作:
1、长按获取长按的ITEM的position — dragPosition 以及对应的view ,手指触摸屏幕的时候,调用onInterceptTouchEvent来获取MotionEvent.ACTION_DOWN事件,获取对应的数据。由于这里是继承了GridView,所以长按时间可以通过setOnItemLongClickListener监听来执行,或则你也可以通过计算点击时间来监听是否长按。
2、通过onTouchEvent(MotionEvent ev)来监听手指的移动和抬起动作。当它移动到 其它的item下面,并且下方的item对应的position 不等于 dragPosition,进行数据交换,并且2者之间的所有item进行移动动画,动画结束后,数据更替刷新界面。
3、抬起手后,清除掉拖动时候创建的view,让GridView中的数据显示。
- 退出时候,将改变后的频道列表存入数据库
DragGrid
public class DragGrid extends GridView {/** 点击时候的X位置 */public int downX;/** 点击时候的Y位置 */public int downY;/** 点击时候对应整个界面的X位置 */public int windowX;/** 点击时候对应整个界面的Y位置 */public int windowY;/** 屏幕上的X */private int win_view_x;/** 屏幕上的Y*/private int win_view_y;/** 拖动的里x的距离 */int dragOffsetX;/** 拖动的里Y的距离 */int dragOffsetY;/** 长按时候对应postion */public int dragPosition;/** Up后对应的ITEM的Position */private int dropPosition;/** 开始拖动的ITEM的Position*/private int startPosition;/** item高 */private int itemHeight;/** item宽 */private int itemWidth;/** 拖动的时候对应ITEM的VIEW */private View dragImageView = null;/** 长按的时候ITEM的VIEW*/private ViewGroup dragItemView = null;/** WindowManager管理器 */private WindowManager windowManager = null;/** */private WindowManager.LayoutParams windowParams = null;/** item总量*/private int itemTotalCount;/** 一行的ITEM数量*/private int nColumns = 4;/** 行数 */private int nRows;/** 剩余部分 */private int Remainder;/** 是否在移动 */private boolean isMoving = false;/** */private int holdPosition;/** 拖动的时候放大的倍数 */private double dragScale = 1.2D;/** 震动器 */private Vibrator mVibrator;/** 每个ITEM之间的水平间距 */private int mHorizontalSpacing = 15;/** 每个ITEM之间的竖直间距 */private int mVerticalSpacing = 15;/* 移动时候最后个动画的ID */private String LastAnimationID;public DragGrid(Context context) {super(context);init(context);}public DragGrid(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);init(context);}public DragGrid(Context context, AttributeSet attrs) {super(context, attrs);init(context);}public void init(Context context){mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);//将布局文件中设置的间距dip转为pxmHorizontalSpacing = DataTools.dip2px(context, mHorizontalSpacing);}@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {// TODO Auto-generated method stubif (ev.getAction() == MotionEvent.ACTION_DOWN) {downX = (int) ev.getX();downY = (int) ev.getY();windowX = (int) ev.getX();windowY = (int) ev.getY();setOnItemClickListener(ev);}return super.onInterceptTouchEvent(ev);}@Overridepublic boolean onTouchEvent(MotionEvent ev) {// TODO Auto-generated method stubboolean bool = true;if (dragImageView != null && dragPosition != AdapterView.INVALID_POSITION) {// 移动时候的对应x,y位置bool = super.onTouchEvent(ev);int x = (int) ev.getX();int y = (int) ev.getY();switch (ev.getAction()) {case MotionEvent.ACTION_DOWN:downX = (int) ev.getX();windowX = (int) ev.getX();downY = (int) ev.getY();windowY = (int) ev.getY();break;case MotionEvent.ACTION_MOVE:onDrag(x, y ,(int) ev.getRawX() , (int) ev.getRawY());if (!isMoving){OnMove(x, y);}if (pointToPosition(x, y) != AdapterView.INVALID_POSITION){break;}break;case MotionEvent.ACTION_UP:stopDrag();onDrop(x, y);requestDisallowInterceptTouchEvent(false);break;default:break;}}return super.onTouchEvent(ev);}/** 在拖动的情况 */private void onDrag(int x, int y , int rawx , int rawy) {if (dragImageView != null) {windowParams.alpha = 0.6f; // windowParams.x = rawx - itemWidth / 2; // windowParams.y = rawy - itemHeight / 2;windowParams.x = rawx - win_view_x;windowParams.y = rawy - win_view_y;windowManager.updateViewLayout(dragImageView, windowParams);}}/** 在松手下放的情况 */private void onDrop(int x, int y) {// 根据拖动到的x,y坐标获取拖动位置下方的ITEM对应的POSTIONint tempPostion = pointToPosition(x, y); // if (tempPostion != AdapterView.INVALID_POSITION) {dropPosition = tempPostion;DragAdapter mDragAdapter = (DragAdapter) getAdapter();//显示刚拖动的ITEMmDragAdapter.setShowDropItem(true);//刷新适配器,让对应的ITEM显示mDragAdapter.notifyDataSetChanged(); // }}/*** 长按点击监听* @param ev*/public void setOnItemClickListener(final MotionEvent ev) {setOnItemLongClickListener(new OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {int x = (int) ev.getX();// 长安事件的X位置int y = (int) ev.getY();// 长安事件的y位置startPosition = position;// 第一次点击的postiondragPosition = position;if (startPosition <= 1) {return false;}ViewGroup dragViewGroup = (ViewGroup) getChildAt(dragPosition - getFirstVisiblePosition());TextView dragTextView = (TextView)dragViewGroup.findViewById(R.id.text_item);dragTextView.setSelected(true);dragTextView.setEnabled(false);itemHeight = dragViewGroup.getHeight();itemWidth = dragViewGroup.getWidth();itemTotalCount = DragGrid.this.getCount();int row = itemTotalCount / nColumns;// 算出行数Remainder = (itemTotalCount % nColumns);// 算出最后一行多余的数量if (Remainder != 0) {nRows = row + 1;} else {nRows = row;}// 如果特殊的这个不等于拖动的那个,并且不等于-1if (dragPosition != AdapterView.INVALID_POSITION) {// 释放的资源使用的绘图缓存。如果你调用buildDrawingCache()手动没有调用setDrawingCacheEnabled(真正的),你应该清理缓存使用这种方法。win_view_x = windowX - dragViewGroup.getLeft();//VIEW相对自己的X,半斤win_view_y = windowY - dragViewGroup.getTop();//VIEW相对自己的y,半斤dragOffsetX = (int) (ev.getRawX() - x);//手指在屏幕的上X位置-手指在控件中的位置就是距离最左边的距离dragOffsetY = (int) (ev.getRawY() - y);//手指在屏幕的上y位置-手指在控件中的位置就是距离最上边的距离dragItemView = dragViewGroup;dragViewGroup.destroyDrawingCache();dragViewGroup.setDrawingCacheEnabled(true);Bitmap dragBitmap = Bitmap.createBitmap(dragViewGroup.getDrawingCache());mVibrator.vibrate(50);//设置震动时间startDrag(dragBitmap, (int)ev.getRawX(), (int)ev.getRawY());hideDropItem();dragViewGroup.setVisibility(View.INVISIBLE);isMoving = false;requestDisallowInterceptTouchEvent(true);return true;}return false;}});}public void startDrag(Bitmap dragBitmap, int x, int y) {stopDrag();windowParams = new WindowManager.LayoutParams();// 获取WINDOW界面的//Gravity.TOP|Gravity.LEFT;这个必须加 windowParams.gravity = Gravity.TOP | Gravity.LEFT; // windowParams.x = x - (int)((itemWidth / 2) * dragScale); // windowParams.y = y - (int) ((itemHeight / 2) * dragScale);//得到preview左上角相对于屏幕的坐标 windowParams.x = x - win_view_x;windowParams.y = y - win_view_y; // this.windowParams.x = (x - this.win_view_x + this.viewX);//位置的x值 // this.windowParams.y = (y - this.win_view_y + this.viewY);//位置的y值//设置拖拽item的宽和高 windowParams.width = (int) (dragScale * dragBitmap.getWidth());// 放大dragScale倍,可以设置拖动后的倍数windowParams.height = (int) (dragScale * dragBitmap.getHeight());// 放大dragScale倍,可以设置拖动后的倍数this.windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;this.windowParams.format = PixelFormat.TRANSLUCENT;this.windowParams.windowAnimations = 0;ImageView iv = new ImageView(getContext());iv.setImageBitmap(dragBitmap);windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);// "window"windowManager.addView(iv, windowParams);dragImageView = iv;}/** 停止拖动 ,释放并初始化 */private void stopDrag() {if (dragImageView != null) {windowManager.removeView(dragImageView);dragImageView = null;}}/** 在ScrollView内,所以要进行计算高度 */@Overridepublic void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);}/** 隐藏 放下 的ITEM*/private void hideDropItem() {((DragAdapter) getAdapter()).setShowDropItem(false);}/** 获取移动动画 */public Animation getMoveAnimation(float toXValue, float toYValue) {TranslateAnimation mTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0F,Animation.RELATIVE_TO_SELF,toXValue, Animation.RELATIVE_TO_SELF, 0.0F,Animation.RELATIVE_TO_SELF, toYValue);// 当前位置移动到指定位置mTranslateAnimation.setFillAfter(true);// 设置一个动画效果执行完毕后,View对象保留在终止的位置。mTranslateAnimation.setDuration(300L);return mTranslateAnimation;}/** 移动的时候触发*/public void OnMove(int x, int y) {// 拖动的VIEW下方的POSTIONint dPosition = pointToPosition(x, y);// 判断下方的POSTION是否是最开始2个不能拖动的if (dPosition > 1) {if ((dPosition == -1) || (dPosition == dragPosition)){return;}dropPosition = dPosition;if (dragPosition != startPosition){dragPosition = startPosition;}int movecount;//拖动的=开始拖的,并且 拖动的 不等于放下的if ((dragPosition == startPosition) || (dragPosition != dropPosition)){//移需要移动的动ITEM数量movecount = dropPosition - dragPosition;}else{//移需要移动的动ITEM数量为0movecount = 0;}if(movecount == 0){return;}int movecount_abs = Math.abs(movecount);if (dPosition != dragPosition) {//dragGroup设置为不可见ViewGroup dragGroup = (ViewGroup) getChildAt(dragPosition);dragGroup.setVisibility(View.INVISIBLE);float to_x = 1;// 当前下方positonfloat to_y;// 当前下方右边positon//x_vlaue移动的距离百分比(相对于自己长度的百分比)float x_vlaue = ((float) mHorizontalSpacing / (float) itemWidth) + 1.0f;//y_vlaue移动的距离百分比(相对于自己宽度的百分比)float y_vlaue = ((float) mVerticalSpacing / (float) itemHeight) + 1.0f;Log.d("x_vlaue", "x_vlaue = " + x_vlaue);for (int i = 0; i < movecount_abs; i++) {to_x = x_vlaue;to_y = y_vlaue;//像左if (movecount > 0) {// 判断是不是同一行的holdPosition = dragPosition + i + 1;if (dragPosition / nColumns == holdPosition / nColumns) {to_x = - x_vlaue;to_y = 0;} else if (holdPosition % 4 == 0) {to_x = 3 * x_vlaue;to_y = - y_vlaue;} else {to_x = - x_vlaue;to_y = 0;}}else{//向右,下移到上,右移到左holdPosition = dragPosition - i - 1;if (dragPosition / nColumns == holdPosition / nColumns) {to_x = x_vlaue;to_y = 0;} else if((holdPosition + 1) % 4 == 0){to_x = -3 * x_vlaue;to_y = y_vlaue;}else{to_x = x_vlaue;to_y = 0;}}ViewGroup moveViewGroup = (ViewGroup) getChildAt(holdPosition);Animation moveAnimation = getMoveAnimation(to_x, to_y);moveViewGroup.startAnimation(moveAnimation);//如果是最后一个移动的,那么设置他的最后个动画ID为LastAnimationIDif (holdPosition == dropPosition) {LastAnimationID = moveAnimation.toString();}moveAnimation.setAnimationListener(new AnimationListener() {@Overridepublic void onAnimationStart(Animation animation) {// TODO Auto-generated method stubisMoving = true;}@Overridepublic void onAnimationRepeat(Animation animation) {// TODO Auto-generated method stub}@Overridepublic void onAnimationEnd(Animation animation) {// TODO Auto-generated method stub// 如果为最后个动画结束,那执行下面的方法if (animation.toString().equalsIgnoreCase(LastAnimationID)) {DragAdapter mDragAdapter = (DragAdapter) getAdapter();mDragAdapter.exchange(startPosition,dropPosition);startPosition = dropPosition;dragPosition = dropPosition;isMoving = false;}}});}}}} }OtherGridView
public class OtherGridView extends GridView {public OtherGridView(Context paramContext, AttributeSet paramAttributeSet) {super(paramContext, paramAttributeSet);}@Overridepublic void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, expandSpec);} }ChannelActivity
public class ChannelActivity extends Activity implements OnItemClickListener {/** 用户栏目的GRIDVIEW */private DragGrid userGridView;/** 其它栏目的GRIDVIEW */private OtherGridView otherGridView;/** 用户栏目对应的适配器,可以拖动 */DragAdapter userAdapter;/** 其它栏目对应的适配器 */OtherAdapter otherAdapter;/** 其它栏目列表 */ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();/** 用户栏目列表 */ArrayList<ChannelItem> userChannelList = new ArrayList<ChannelItem>();/** 是否在移动,由于这边是动画结束后才进行的数据更替,设置这个限制为了避免操作太频繁造成的数据错乱。 */ boolean isMove = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.subscribe_activity);initView();initData();}/** 初始化数据*/private void initData() {userChannelList = ((ArrayList<ChannelItem>)ChannelManage.getManage(AppApplication.getApp().getSQLHelper()).getUserChannel());otherChannelList = ((ArrayList<ChannelItem>)ChannelManage.getManage(AppApplication.getApp().getSQLHelper()).getOtherChannel());userAdapter = new DragAdapter(this, userChannelList);userGridView.setAdapter(userAdapter);otherAdapter = new OtherAdapter(this, otherChannelList);otherGridView.setAdapter(this.otherAdapter);//设置GRIDVIEW的ITEM的点击监听otherGridView.setOnItemClickListener(this);userGridView.setOnItemClickListener(this);}/** 初始化布局*/private void initView() {userGridView = (DragGrid) findViewById(R.id.userGridView);otherGridView = (OtherGridView) findViewById(R.id.otherGridView);}@Overridepublic 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;}/** GRIDVIEW对应的ITEM点击监听接口 */@Overridepublic void onItemClick(AdapterView<?> parent, final View view, final int position,long id) {//如果点击的时候,之前动画还没结束,那么就让点击事件无效if(isMove){return;}switch (parent.getId()) {case R.id.userGridView://position为 0,1 的不可以进行任何操作if (position != 0 && position != 1) {final ImageView moveImageView = getView(view);if (moveImageView != null) {TextView newTextView = (TextView) view.findViewById(R.id.text_item);final int[] startLocation = new int[2];newTextView.getLocationInWindow(startLocation);final ChannelItem channel = ((DragAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容otherAdapter.setVisible(false);//添加到最后一个otherAdapter.addItem(channel);new Handler().postDelayed(new Runnable() {public void run() {try {int[] endLocation = new int[2];//获取终点的坐标otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);MoveAnim(moveImageView, startLocation , endLocation, channel,userGridView);userAdapter.setRemove(position);} catch (Exception localException) {}}}, 50L);}}break;case R.id.otherGridView:final ImageView moveImageView = getView(view);if (moveImageView != null){TextView newTextView = (TextView) view.findViewById(R.id.text_item);final int[] startLocation = new int[2];newTextView.getLocationInWindow(startLocation);final ChannelItem channel = ((OtherAdapter) parent.getAdapter()).getItem(position);userAdapter.setVisible(false);//添加到最后一个userAdapter.addItem(channel);new Handler().postDelayed(new Runnable() {public void run() {try {int[] endLocation = new int[2];//获取终点的坐标userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);MoveAnim(moveImageView, startLocation , endLocation, channel,otherGridView);otherAdapter.setRemove(position);} catch (Exception localException) {}}}, 50L);}break;default:break;}}/*** 点击ITEM移动动画* @param moveView* @param startLocation* @param endLocation* @param moveChannel* @param clickGridView*/private void MoveAnim(View moveView, int[] startLocation,int[] endLocation, final ChannelItem moveChannel,final GridView clickGridView) {int[] initLocation = new int[2];//获取传递过来的VIEW的坐标moveView.getLocationInWindow(initLocation);//得到要移动的VIEW,并放入对应的容器中final ViewGroup moveViewGroup = getMoveViewGroup();final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);//创建移动动画TranslateAnimation moveAnimation = new TranslateAnimation(startLocation[0], endLocation[0], startLocation[1],endLocation[1]);moveAnimation.setDuration(300L);//动画时间//动画配置AnimationSet moveAnimationSet = new AnimationSet(true);moveAnimationSet.setFillAfter(false);//动画效果执行完毕后,View对象不保留在终止的位置moveAnimationSet.addAnimation(moveAnimation);mMoveView.startAnimation(moveAnimationSet);moveAnimationSet.setAnimationListener(new AnimationListener() {@Overridepublic void onAnimationStart(Animation animation) {isMove = true;}@Overridepublic void onAnimationRepeat(Animation animation) {}@Overridepublic void onAnimationEnd(Animation animation) {moveViewGroup.removeView(mMoveView);// instanceof 方法判断2边实例是不是一样,判断点击的是DragGrid还是OtherGridViewif (clickGridView instanceof DragGrid) {otherAdapter.setVisible(true);otherAdapter.notifyDataSetChanged();userAdapter.remove();}else{userAdapter.setVisible(true);userAdapter.notifyDataSetChanged();otherAdapter.remove();}isMove = false;}});}/*** 获取移动的VIEW,放入对应ViewGroup布局容器* @param viewGroup* @param view* @param initLocation* @return*/private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {int x = initLocation[0];int y = initLocation[1];viewGroup.addView(view);LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);mLayoutParams.leftMargin = x;mLayoutParams.topMargin = y;view.setLayoutParams(mLayoutParams);return view;}/*** 创建移动的ITEM对应的ViewGroup布局容器*/private ViewGroup getMoveViewGroup() {ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();LinearLayout moveLinearLayout = new LinearLayout(this);moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));moveViewGroup.addView(moveLinearLayout);return moveLinearLayout;}/*** 获取点击的Item的对应View,* @param view* @return*/private ImageView getView(View view) {view.destroyDrawingCache();view.setDrawingCacheEnabled(true);Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());view.setDrawingCacheEnabled(false);ImageView iv = new ImageView(this);iv.setImageBitmap(cache);return iv;}/** 退出时候保存选择后数据库的设置 */private void saveChannel() {ChannelManage.getManage(AppApplication.getApp().getSQLHelper()).deleteAllChannel();ChannelManage.getManage(AppApplication.getApp().getSQLHelper()).saveUserChannel(userAdapter.getChannnelLst());ChannelManage.getManage(AppApplication.getApp().getSQLHelper()).saveOtherChannel(otherAdapter.getChannnelLst());}@Overridepublic void onBackPressed() {saveChannel();super.onBackPressed();} }DragAdapter
public class DragAdapter extends BaseAdapter {/** TAG*/private final static String TAG = "DragAdapter";/** 是否显示底部的ITEM */private boolean isItemShow = false;private Context context;/** 控制的postion */private int holdPosition;/** 是否改变 */private boolean isChanged = false;/** 是否可见 */boolean isVisible = true;/** 可以拖动的列表(即用户选择的频道列表) */public List<ChannelItem> channelList;/** TextView 频道内容 */private TextView item_text;/** 要删除的position */public int remove_position = -1;public DragAdapter(Context context, List<ChannelItem> channelList) {this.context = context;this.channelList = channelList;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn channelList == null ? 0 : channelList.size();}@Overridepublic ChannelItem getItem(int position) {// TODO Auto-generated method stubif (channelList != null && channelList.size() != 0) {return channelList.get(position);}return null;}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view = LayoutInflater.from(context).inflate(R.layout.subscribe_category_item, null);item_text = (TextView) view.findViewById(R.id.text_item);ChannelItem channel = getItem(position);item_text.setText(channel.getName());if ((position == 0) || (position == 1)){ // item_text.setTextColor(context.getResources().getColor(R.color.black));item_text.setEnabled(false);}if (isChanged && (position == holdPosition) && !isItemShow) {item_text.setText("");item_text.setSelected(true);item_text.setEnabled(true);isChanged = false;}if (!isVisible && (position == -1 + channelList.size())) {item_text.setText("");item_text.setSelected(true);item_text.setEnabled(true);}if(remove_position == position){item_text.setText("");}return view;}/** 添加频道列表 */public void addItem(ChannelItem channel) {channelList.add(channel);notifyDataSetChanged();}/** 拖动变更频道排序 */public void exchange(int dragPostion, int dropPostion) {holdPosition = dropPostion;ChannelItem dragItem = getItem(dragPostion);Log.d(TAG, "startPostion=" + dragPostion + ";endPosition=" + dropPostion);if (dragPostion < dropPostion) {channelList.add(dropPostion + 1, dragItem);channelList.remove(dragPostion);} else {channelList.add(dropPostion, dragItem);channelList.remove(dragPostion + 1);}isChanged = true;notifyDataSetChanged();}/** 获取频道列表 */public List<ChannelItem> getChannnelLst() {return channelList;}/** 设置删除的position */public void setRemove(int position) {remove_position = position;notifyDataSetChanged();}/** 删除频道列表 */public void remove() {channelList.remove(remove_position);remove_position = -1;notifyDataSetChanged();}/** 设置频道列表 */public void setListDate(List<ChannelItem> list) {channelList = list;}/** 获取是否可见 */public boolean isVisible() {return isVisible;}/** 设置是否可见 */public void setVisible(boolean visible) {isVisible = visible;}/** 显示放下的ITEM */public void setShowDropItem(boolean show) {isItemShow = show;} }OtherAdapter
public class OtherAdapter extends BaseAdapter {private Context context;public List<ChannelItem> channelList;private TextView item_text;/** 是否可见 */boolean isVisible = true;/** 要删除的position */public int remove_position = -1;public OtherAdapter(Context context, List<ChannelItem> channelList) {this.context = context;this.channelList = channelList;}@Overridepublic int getCount() {return channelList == null ? 0 : channelList.size();}@Overridepublic ChannelItem getItem(int position) {if (channelList != null && channelList.size() != 0) {return channelList.get(position);}return null;}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view = LayoutInflater.from(context).inflate(R.layout.subscribe_category_item, null);item_text = (TextView) view.findViewById(R.id.text_item);ChannelItem channel = getItem(position);item_text.setText(channel.getName());if (!isVisible && (position == -1 + channelList.size())){item_text.setText("");}if(remove_position == position){item_text.setText("");}return view;}/** 获取频道列表 */public List<ChannelItem> getChannnelLst() {return channelList;}/** 添加频道列表 */public void addItem(ChannelItem channel) {channelList.add(channel);notifyDataSetChanged();}/** 设置删除的position */public void setRemove(int position) {remove_position = position;notifyDataSetChanged();// notifyDataSetChanged();}/** 删除频道列表 */public void remove() {channelList.remove(remove_position);remove_position = -1;notifyDataSetChanged();}/** 设置频道列表 */public void setListDate(List<ChannelItem> list) {channelList = list;}/** 获取是否可见 */public boolean isVisible() {return isVisible;}/** 设置是否可见 */public void setVisible(boolean visible) {isVisible = visible;} }ChannelManage
public class ChannelManage {public static ChannelManage channelManage;/*** 默认的用户选择频道列表* */public static List<ChannelItem> defaultUserChannels;/*** 默认的其他频道列表* */public static List<ChannelItem> defaultOtherChannels;private ChannelDao channelDao;/** 判断数据库中是否存在用户数据 */private boolean userExist = false;static {defaultUserChannels = new ArrayList<ChannelItem>();defaultOtherChannels = new ArrayList<ChannelItem>();defaultUserChannels.add(new ChannelItem(1, "推荐", 1, 1));defaultUserChannels.add(new ChannelItem(2, "热点", 2, 1));defaultUserChannels.add(new ChannelItem(3, "娱乐", 3, 1));defaultUserChannels.add(new ChannelItem(4, "时尚", 4, 1));defaultUserChannels.add(new ChannelItem(5, "科技", 5, 1));defaultUserChannels.add(new ChannelItem(6, "体育", 6, 1));defaultUserChannels.add(new ChannelItem(7, "军事", 7, 1));defaultOtherChannels.add(new ChannelItem(8, "财经", 1, 0));defaultOtherChannels.add(new ChannelItem(9, "汽车", 2, 0));defaultOtherChannels.add(new ChannelItem(10, "房产", 3, 0));defaultOtherChannels.add(new ChannelItem(11, "社会", 4, 0));defaultOtherChannels.add(new ChannelItem(12, "情感", 5, 0));defaultOtherChannels.add(new ChannelItem(13, "女人", 6, 0));defaultOtherChannels.add(new ChannelItem(14, "旅游", 7, 0));defaultOtherChannels.add(new ChannelItem(15, "健康", 8, 0));defaultOtherChannels.add(new ChannelItem(16, "美女", 9, 0));defaultOtherChannels.add(new ChannelItem(17, "游戏", 10, 0));defaultOtherChannels.add(new ChannelItem(18, "数码", 11, 0));}private ChannelManage(SQLHelper paramDBHelper) throws SQLException {if (channelDao == null)channelDao = new ChannelDao(paramDBHelper.getContext());// NavigateItemDao(paramDBHelper.getDao(NavigateItem.class));return;}/*** 初始化频道管理类* @param paramDBHelper* @throws SQLException*/public static ChannelManage getManage(SQLHelper dbHelper)throws SQLException {if (channelManage == null)channelManage = new ChannelManage(dbHelper);return channelManage;}/*** 清除所有的频道*/public void deleteAllChannel() {channelDao.clearFeedTable();}/*** 获取其他的频道* @return 数据库存在用户配置 ? 数据库内的用户选择频道 : 默认用户选择频道 ;*/public List<ChannelItem> getUserChannel() {Object cacheList = channelDao.listCache(SQLHelper.SELECTED + "= ?",new String[] { "1" });if (cacheList != null && !((List) cacheList).isEmpty()) {userExist = true;List<Map<String, String>> maplist = (List) cacheList;int count = maplist.size();List<ChannelItem> list = new ArrayList<ChannelItem>();for (int i = 0; i < count; i++) {ChannelItem navigate = new ChannelItem();navigate.setId(Integer.valueOf(maplist.get(i).get(SQLHelper.ID)));navigate.setName(maplist.get(i).get(SQLHelper.NAME));navigate.setOrderId(Integer.valueOf(maplist.get(i).get(SQLHelper.ORDERID)));navigate.setSelected(Integer.valueOf(maplist.get(i).get(SQLHelper.SELECTED)));list.add(navigate);}return list;}initDefaultChannel();return defaultUserChannels;}/*** 获取其他的频道* @return 数据库存在用户配置 ? 数据库内的其它频道 : 默认其它频道 ;*/public List<ChannelItem> getOtherChannel() {Object cacheList = channelDao.listCache(SQLHelper.SELECTED + "= ?" ,new String[] { "0" });List<ChannelItem> list = new ArrayList<ChannelItem>();if (cacheList != null && !((List) cacheList).isEmpty()){List<Map<String, String>> maplist = (List) cacheList;int count = maplist.size();for (int i = 0; i < count; i++) {ChannelItem navigate= new ChannelItem();navigate.setId(Integer.valueOf(maplist.get(i).get(SQLHelper.ID)));navigate.setName(maplist.get(i).get(SQLHelper.NAME));navigate.setOrderId(Integer.valueOf(maplist.get(i).get(SQLHelper.ORDERID)));navigate.setSelected(Integer.valueOf(maplist.get(i).get(SQLHelper.SELECTED)));list.add(navigate);}return list;}if(userExist){return list;}cacheList = defaultOtherChannels;return (List<ChannelItem>) cacheList;}/*** 保存用户频道到数据库* @param userList*/public void saveUserChannel(List<ChannelItem> userList) {for (int i = 0; i < userList.size(); i++) {ChannelItem channelItem = (ChannelItem) userList.get(i);channelItem.setOrderId(i);channelItem.setSelected(Integer.valueOf(1));channelDao.addCache(channelItem);}}/*** 保存其他频道到数据库* @param otherList*/public void saveOtherChannel(List<ChannelItem> otherList) {for (int i = 0; i < otherList.size(); i++) {ChannelItem channelItem = (ChannelItem) otherList.get(i);channelItem.setOrderId(i);channelItem.setSelected(Integer.valueOf(0));channelDao.addCache(channelItem);}}/*** 初始化数据库内的频道数据*/private void initDefaultChannel(){Log.d("deleteAll", "deleteAll");deleteAllChannel();saveUserChannel(defaultUserChannels);saveOtherChannel(defaultOtherChannels);} }总结
- 上一篇: Gson使用指南
- 下一篇: Could not get unknow