新闻阅读器频道管理
原文鏈接: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