Android(Java):滑動刪除實現——重寫onTouch

public class RecordFragment extends Fragment{
 
 private int userId;
 private List datas;
 
 private View mVNorecord;
 private View mVRecord;
 private Button mBtnClear;
 private ListView mLvRecord;
 private RecordAdapter mRecordAdapter;
 private StudyLogDao studyLogDao;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
 }

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

 @Override
 public void onViewCreated(View view, Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onViewCreated(view, savedInstanceState);
  initView(view);
  initData();
 }

 private void initData() {
  // TODO Auto-generated method stub
  if(loadData()){
   return;
  }
  userId = GlobalModel.getInstance().getUser().getUid();
  StudyLog data;
  int i;
  for(i=0;i<20;i++){
   data = new StudyLog();
   data.setUserId(userId);
   data.setSectionName("會計課堂"+i);
   data.setSectionId(i+1);
   data.setCoursewareId(i+1);
   data.setCurPostion((95+i)>100?0:(95+i));
   data.setStatus((short) View.GONE);
   studyLogDao.insert(data);
  }
  loadData();
 }
 
 private boolean loadData(){
  
  datas = studyLogDao.queryByUserId(userId);
  mRecordAdapter.setRecords(datas);
  if(datas.size()>0){
   mVRecord.setVisibility(View.VISIBLE);
   mVNorecord.setVisibility(View.GONE);
   return true;
  }
  mVNorecord.setVisibility(View.VISIBLE);
  mVRecord.setVisibility(View.GONE);
  return false;
 }

 private void initView(View view) {
  // TODO Auto-generated method stub
  mVNorecord = view.findViewById(R.id.norecord);
  mVRecord = view.findViewById(R.id.recordlist);
  mBtnClear = (Button) view.findViewById(R.id.clear);
  mLvRecord =  (ListView) view.findViewById(R.id.record_learning_lv);
  
  mRecordAdapter = new RecordAdapter(this.getActivity(), null);
  mLvRecord.setAdapter(mRecordAdapter);
  /*mLvRecord.setOnTouchListener(new OnTouchListener() {
   View v = null;
   StudyLog studyLog = null;
   float x, y, ux, uy;
   public boolean onTouch(View view, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) { 
                    x = event.getX();
                    y = event.getY();
                }else if (event.getAction() == MotionEvent.ACTION_UP) { 
                 ux = event.getX();
                 uy = event.getY();
                    int position1 = ((ListView) view).pointToPosition((int) x, (int) y); 
                    int position2 = ((ListView) view).pointToPosition((int) ux,(int) uy);
                    if(position1!=position2){
                     return false;
                    }
                    v = ((ListView) view).getChildAt(position1);
                    if(null == v){
                     return false;
                    }
                 if (ux - x > 10) {
                  mRecordAdapter.removeListItem(v,position1,false);
                    }else{
                     studyLog = mRecordAdapter.getRecords().get(position1);
            if(studyLog.getStatus() == View.VISIBLE){
             studyLog.setStatus((short) View.GONE);
            }
            mRecordAdapter.notifyDataSetChanged();
            
            Course course = studyLogDao.getCourse(studyLog.getExamId(), studyLog.getSubjectId(), studyLog.getCourseId());
            if (course.getProgress().contains("關閉")) {
             new AlertDialog.Builder(getActivity())
       .setTitle("提示")
       .setMessage("很抱歉,本課程已關閉")
       .setPositiveButton("確定",null).show();
             return false;
            }
            Intent intent = new Intent(getActivity(), PlayVideoActivity.class);
            intent.putExtras(studyLog.getParams());
            getActivity().startActivity(intent);
                    }
                }
    return false;
   }
  });
  mLvRecord.setOnItemClickListener(new OnItemClickListener(){
   StudyLog studyLog = null;
   @Override
   public void onItemClick(AdapterView<?> paramAdapterView,
     View paramView, int paramInt, long paramLong) {
    // TODO Auto-generated method stub
    studyLog = mRecordAdapter.getRecords().get(paramInt);
    Course course = studyLogDao.getCourse(studyLog.getExamId(), studyLog.getSubjectId(), studyLog.getCourseId());
    if (course.getProgress().contains("關閉")) {
     new AlertDialog.Builder(getActivity())
     .setTitle("提示")
     .setMessage("很抱歉,本課程已關閉")
     .setPositiveButton("確定",null).show();
    }
    Intent intent = new Intent(getActivity(), PlayVideoActivity.class);
    intent.putExtras(studyLog.getParams());
    getActivity().startActivity(intent);
   }
   
  });*/

  mBtnClear.setOnClickListener(btnClickListener);
  studyLogDao = new StudyLogDao(getActivity());
 }
 
 private OnClickListener btnClickListener = new OnClickListener() {
  @Override
  public void onClick(View v) {
   
   studyLogDao.deleteByUserId(userId);
   loadData();
   new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.notify))
   .setMessage(R.string.clearsuccess)
   .setPositiveButton(getString(R.string.ok), null).show();
  }
 };
}

public class RecordAdapter extends BaseAdapter {
 
 private Context mContext;
 private List<StudyLog> records;
 private LayoutInflater mLayoutInflater;
 private StudyLogDao studyLogDao;
 
 private static final int LIST_HEIGHT = 50;
 
 public RecordAdapter(Context context, List<StudyLog> records){
  this.mContext = context;
  this.records = records;
  this.mLayoutInflater = LayoutInflater.from(context);
  studyLogDao  = new StudyLogDao(context);
 }

 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  if(records == null)
   return 0;
  return records.size();
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return records.get(position);
 }

 @Override
 public long getItemId(int position) {
  return 0;
 }

 @Override
 public View getView(final int position, View convertView, ViewGroup parent) {
  // TODO Auto-generated method stub
  ViewHolder viewHolder = null;
  if(convertView == null) {
   viewHolder = new ViewHolder();
   convertView = mLayoutInflater.inflate(R.layout.item_record_list, null);
   viewHolder.tvName = (TextView) convertView.findViewById(R.id.rtv_name);
   viewHolder.tvRecord = (TextView) convertView.findViewById(R.id.rtv_record);
   viewHolder.btnDelete = (Button) convertView.findViewById(R.id.recorddel);
   //設置行高度
   AbsListView.LayoutParams params=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LayoutManager.dip2px(mContext, LIST_HEIGHT));
   convertView.setLayoutParams(params);
   convertView.setTag(viewHolder);
  }else {
   viewHolder = (ViewHolder) convertView.getTag();
  }

   convertView.setOnTouchListener(new OnTouchListener() {
   StudyLog studyLog = null;
   float x, ux;
   public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) { 
                    v.setBackgroundResource(R.color.dongao_orange);
                    x = event.getX();
                }else if (event.getAction() == MotionEvent.ACTION_UP) {
                 v.setBackgroundResource(android.R.color.white);
                 ux = event.getX();
                 if (ux - x > 10) {
                  removeListItem(v,position,false);
                    }else{
                     studyLog = records.get(position);
            if(studyLog.getStatus() == View.VISIBLE){
             studyLog.setStatus((short) View.GONE);
            }
            notifyDataSetChanged();
            
            Bundle bundle = studyLog.getParams();
            if (bundle.getBoolean("isClose")) {
             new AlertDialog.Builder(mContext)
       .setTitle("提示")
       .setMessage("很抱歉,本課程已關閉")
       .setPositiveButton("確定",null).show();
             return true;
            }
            Intent intent = new Intent(mContext, PlayVideoActivity.class);
            intent.putExtras(bundle);
            mContext.startActivity(intent);
                    }
                }else{
                 v.setBackgroundResource(android.R.color.white);
                }
    return true;
   }
  });
  StudyLog record = records.get(position);
  viewHolder.tvName.setText(record.getSectionName());
  viewHolder.tvRecord.setText(record.getLog());
  viewHolder.btnDelete.setVisibility(record.getStatus());
  return convertView;
 }
 
 public void removeListItem(final View v, final int position, final boolean delete) {
  // TODO Auto-generated method stub
   final Animation animation = (Animation) AnimationUtils.loadAnimation(mContext, R.anim.item_anim); 
   animation.setAnimationListener(new AnimationListener() {
   boolean run = false;
   ViewHolder viewHolder = null;
   View view;
   StudyLog record;
            public void onAnimationStart(Animation animation) {} 
            public void onAnimationRepeat(Animation animation) {} 
            public void onAnimationEnd(Animation animation) {
             if(run){
              return;
             }
             //view = v.findViewById(R.id.recorddel);
             viewHolder = (ViewHolder) v.getTag();
             view = viewHolder.btnDelete;
             record = records.get(position);
             if(delete) {
              //records.remove(position);
              studyLogDao.deleteById(record.getUid());
              setRecords(studyLogDao.queryByUserId(record.getUserId()));
              record.setStatus((short)View.GONE);
              //record.put("visibility", String.valueOf(View.GONE));
             }else{
              if(record.getStatus() == View.GONE){
               record.setStatus((short)View.VISIBLE);
              }else{
               record.setStatus((short)View.GONE);
              }
           //record.put("visibility", String.valueOf(View.VISIBLE));
              view.setOnClickListener(new OnClickListener(){

      @Override
      public void onClick(View paramView) {
       // TODO Auto-generated method stub
       removeListItem(v,position,true);
      }
               
              });
             }
                notifyDataSetChanged(); 
                animation.cancel();
                run = true;
            }
        });
        v.startAnimation(animation);    
 }
 
private final static class ViewHolder{
  
  TextView tvName;
  TextView tvRecord;
  Button btnDelete;
 }

 public List<StudyLog> getRecords() {
  return records;
 }

 public void setRecords(List<StudyLog> records) {
  this.records = records;
  this.notifyDataSetChanged();
 }

 public void clear() {
  // TODO Auto-generated method stub
  records.clear();
  this.notifyDataSetChanged();
 }
}

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromXDelta="0" android:toXDelta="100%p"
  android:duration="300" />
</set>

<?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:orientation="vertical" >
    <RelativeLayout
        android:id="@+id/norecord"
        android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >
 <ImageView
             android:id="@+id/recordiv"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_centerHorizontal="true"
             android:layout_centerVertical="true"
             android:src="@drawable/record"
             />
 
 <TextView
     android:id="@+id/recordtv"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_below="@id/recordiv"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="8dip"
     android:text="沒有學習記錄,快去學習吧!"
     android:textSize="17sp" />
 </RelativeLayout>
 <RelativeLayout
     android:id="@+id/recordlist"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical">
 <ListView
     android:id="@+id/record_learning_lv"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:layout_margin="15dp"
     android:divider="@null"
     />
 <Button
         android:id="@+id/clear"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_alignParentRight="true"
         android:text="@string/clear"
         android:layout_marginRight="15dp"
         android:layout_marginBottom="25dp"
         android:textSize="17sp"
        android:textColor="@android:color/white"
         android:background="@drawable/btn_clear_selected"
         />
 </RelativeLayout>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/riv_arraw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dip"
        android:src="@drawable/arraw" />

    <TextView
        android:id="@+id/rtv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dip"
        android:layout_toRightOf="@id/riv_arraw"
        android:textColor="#76715E"
        android:textSize="17sp" />
  
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        >
    <TextView
        android:id="@+id/rtv_record"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:textSize="12sp" />
   
    <Button
        android:id="@+id/recorddel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/rtv_record"
        android:layout_centerVertical="true"
     android:background="@drawable/delete"
     android:visibility="gone"
        />
    </RelativeLayout>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="1dip"
        android:layout_alignParentBottom="true"
        android:scaleType="fitXY"
        android:src="@drawable/divider" />

</RelativeLayout>

 

發佈了51 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章