原文連結:http://blog.csdn.net/vipzjyno1/article/details/25005851
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLxIDOx81N0YDM1ITO5MTMvwVNw8CX1ADNxAjMvw1ckF2bsBXdvwFdl5mLuR2cj5Set1yZtl2Lc9CX6MHc0RHaiojIsJye.gif)
本例子實作的功能是很多新聞閱讀器(網易,今日頭條,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 = ;
/** 行數 */
private int nRows;
/** 剩餘部分 */
private int Remainder;
/** 是否在移動 */
private boolean isMoving = false;
/** */
private int holdPosition;
/** 拖動的時候放大的倍數 */
private double dragScale = D;
/** 震動器 */
private Vibrator mVibrator;
/** 每個ITEM之間的水準間距 */
private int mHorizontalSpacing = ;
/** 每個ITEM之間的豎直間距 */
private int mVerticalSpacing = ;
/* 移動時候最後個動畫的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轉為px
mHorizontalSpacing = DataTools.dip2px(context, mHorizontalSpacing);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
if (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);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
boolean 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 = f;
// 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對應的POSTION
int tempPostion = pointToPosition(x, y);
// if (tempPostion != AdapterView.INVALID_POSITION) {
dropPosition = tempPostion;
DragAdapter mDragAdapter = (DragAdapter) getAdapter();
//顯示剛拖動的ITEM
mDragAdapter.setShowDropItem(true);
//重新整理擴充卡,讓對應的ITEM顯示
mDragAdapter.notifyDataSetChanged();
// }
}
/**
* 長按點選監聽
* @param ev
*/
public void setOnItemClickListener(final MotionEvent ev) {
setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
int x = (int) ev.getX();// 長安事件的X位置
int y = (int) ev.getY();// 長安事件的y位置
startPosition = position;// 第一次點選的postion
dragPosition = position;
if (startPosition <= ) {
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 != ) {
nRows = row + ;
} else {
nRows = row;
}
// 如果特殊的這個不等于拖動的那個,并且不等于-1
if (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();//設定震動時間
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 = ;
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内,是以要進行計算高度 */
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> ,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, F,
Animation.RELATIVE_TO_SELF,toXValue,
Animation.RELATIVE_TO_SELF, F,
Animation.RELATIVE_TO_SELF, toYValue);// 目前位置移動到指定位置
mTranslateAnimation.setFillAfter(true);// 設定一個動畫效果執行完畢後,View對象保留在終止的位置。
mTranslateAnimation.setDuration(L);
return mTranslateAnimation;
}
/** 移動的時候觸發*/
public void OnMove(int x, int y) {
// 拖動的VIEW下方的POSTION
int dPosition = pointToPosition(x, y);
// 判斷下方的POSTION是否是最開始2個不能拖動的
if (dPosition > ) {
if ((dPosition == -) || (dPosition == dragPosition)){
return;
}
dropPosition = dPosition;
if (dragPosition != startPosition){
dragPosition = startPosition;
}
int movecount;
//拖動的=開始拖的,并且 拖動的 不等于放下的
if ((dragPosition == startPosition) || (dragPosition != dropPosition)){
//移需要移動的動ITEM數量
movecount = dropPosition - dragPosition;
}else{
//移需要移動的動ITEM數量為0
movecount = ;
}
if(movecount == ){
return;
}
int movecount_abs = Math.abs(movecount);
if (dPosition != dragPosition) {
//dragGroup設定為不可見
ViewGroup dragGroup = (ViewGroup) getChildAt(dragPosition);
dragGroup.setVisibility(View.INVISIBLE);
float to_x = ;// 目前下方positon
float to_y;// 目前下方右邊positon
//x_vlaue移動的距離百分比(相對于自己長度的百分比)
float x_vlaue = ((float) mHorizontalSpacing / (float) itemWidth) + f;
//y_vlaue移動的距離百分比(相對于自己寬度的百分比)
float y_vlaue = ((float) mVerticalSpacing / (float) itemHeight) + f;
Log.d("x_vlaue", "x_vlaue = " + x_vlaue);
for (int i = ; i < movecount_abs; i++) {
to_x = x_vlaue;
to_y = y_vlaue;
//像左
if (movecount > ) {
// 判斷是不是同一行的
holdPosition = dragPosition + i + ;
if (dragPosition / nColumns == holdPosition / nColumns) {
to_x = - x_vlaue;
to_y = ;
} else if (holdPosition % == ) {
to_x = * x_vlaue;
to_y = - y_vlaue;
} else {
to_x = - x_vlaue;
to_y = ;
}
}else{
//向右,下移到上,右移到左
holdPosition = dragPosition - i - ;
if (dragPosition / nColumns == holdPosition / nColumns) {
to_x = x_vlaue;
to_y = ;
} else if((holdPosition + ) % == ){
to_x = - * x_vlaue;
to_y = y_vlaue;
}else{
to_x = x_vlaue;
to_y = ;
}
}
ViewGroup moveViewGroup = (ViewGroup) getChildAt(holdPosition);
Animation moveAnimation = getMoveAnimation(to_x, to_y);
moveViewGroup.startAnimation(moveAnimation);
//如果是最後一個移動的,那麼設定他的最後個動畫ID為LastAnimationID
if (holdPosition == dropPosition) {
LastAnimationID = moveAnimation.toString();
}
moveAnimation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
isMoving = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public 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);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> ,
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;
@Override
protected 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);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** GRIDVIEW對應的ITEM點選監聽接口 */
@Override
public 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 != && position != ) {
final ImageView moveImageView = getView(view);
if (moveImageView != null) {
TextView newTextView = (TextView) view.findViewById(R.id.text_item);
final int[] startLocation = new int[];
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[];
//擷取終點的坐标
otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
MoveAnim(moveImageView, startLocation , endLocation, channel,userGridView);
userAdapter.setRemove(position);
} catch (Exception localException) {
}
}
}, L);
}
}
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[];
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[];
//擷取終點的坐标
userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
MoveAnim(moveImageView, startLocation , endLocation, channel,otherGridView);
otherAdapter.setRemove(position);
} catch (Exception localException) {
}
}
}, L);
}
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[];
//擷取傳遞過來的VIEW的坐标
moveView.getLocationInWindow(initLocation);
//得到要移動的VIEW,并放入對應的容器中
final ViewGroup moveViewGroup = getMoveViewGroup();
final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
//建立移動動畫
TranslateAnimation moveAnimation = new TranslateAnimation(
startLocation[], endLocation[], startLocation[],
endLocation[]);
moveAnimation.setDuration(L);//動畫時間
//動畫配置
AnimationSet moveAnimationSet = new AnimationSet(true);
moveAnimationSet.setFillAfter(false);//動畫效果執行完畢後,View對象不保留在終止的位置
moveAnimationSet.addAnimation(moveAnimation);
mMoveView.startAnimation(moveAnimationSet);
moveAnimationSet.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
isMove = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
moveViewGroup.removeView(mMoveView);
// instanceof 方法判斷2邊執行個體是不是一樣,判斷點選的是DragGrid還是OtherGridView
if (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[];
int y = initLocation[];
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());
}
@Override
public 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 = -;
public DragAdapter(Context context, List<ChannelItem> channelList) {
this.context = context;
this.channelList = channelList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return channelList == null ? : channelList.size();
}
@Override
public ChannelItem getItem(int position) {
// TODO Auto-generated method stub
if (channelList != null && channelList.size() != ) {
return channelList.get(position);
}
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public 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 == ) || (position == )){
// 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 == - + 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 + , dragItem);
channelList.remove(dragPostion);
} else {
channelList.add(dropPostion, dragItem);
channelList.remove(dragPostion + );
}
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 = -;
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 = -;
public OtherAdapter(Context context, List<ChannelItem> channelList) {
this.context = context;
this.channelList = channelList;
}
@Override
public int getCount() {
return channelList == null ? : channelList.size();
}
@Override
public ChannelItem getItem(int position) {
if (channelList != null && channelList.size() != ) {
return channelList.get(position);
}
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public 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 == - + 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 = -;
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(, "推薦", , ));
defaultUserChannels.add(new ChannelItem(, "熱點", , ));
defaultUserChannels.add(new ChannelItem(, "娛樂", , ));
defaultUserChannels.add(new ChannelItem(, "時尚", , ));
defaultUserChannels.add(new ChannelItem(, "科技", , ));
defaultUserChannels.add(new ChannelItem(, "體育", , ));
defaultUserChannels.add(new ChannelItem(, "軍事", , ));
defaultOtherChannels.add(new ChannelItem(, "财經", , ));
defaultOtherChannels.add(new ChannelItem(, "汽車", , ));
defaultOtherChannels.add(new ChannelItem(, "房産", , ));
defaultOtherChannels.add(new ChannelItem(, "社會", , ));
defaultOtherChannels.add(new ChannelItem(, "情感", , ));
defaultOtherChannels.add(new ChannelItem(, "女人", , ));
defaultOtherChannels.add(new ChannelItem(, "旅遊", , ));
defaultOtherChannels.add(new ChannelItem(, "健康", , ));
defaultOtherChannels.add(new ChannelItem(, "美女", , ));
defaultOtherChannels.add(new ChannelItem(, "遊戲", , ));
defaultOtherChannels.add(new ChannelItem(, "數位", , ));
}
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 = ; 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 = ; 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 = ; i < userList.size(); i++) {
ChannelItem channelItem = (ChannelItem) userList.get(i);
channelItem.setOrderId(i);
channelItem.setSelected(Integer.valueOf());
channelDao.addCache(channelItem);
}
}
/**
* 儲存其他頻道到資料庫
* @param otherList
*/
public void saveOtherChannel(List<ChannelItem> otherList) {
for (int i = ; i < otherList.size(); i++) {
ChannelItem channelItem = (ChannelItem) otherList.get(i);
channelItem.setOrderId(i);
channelItem.setSelected(Integer.valueOf());
channelDao.addCache(channelItem);
}
}
/**
* 初始化資料庫内的頻道資料
*/
private void initDefaultChannel(){
Log.d("deleteAll", "deleteAll");
deleteAllChannel();
saveUserChannel(defaultUserChannels);
saveOtherChannel(defaultOtherChannels);
}
}