Android自定義view——側(cè)滑可刪除的listView

實現(xiàn)了一個可側(cè)滑刪除的listView刹淌,這個view是一個繼承自listView的自定義view,
實現(xiàn)側(cè)滑刪除穴张,可以通過很多種方式巩剖,今天我介紹的方式是通過PopupWindow的方式來實現(xiàn)的。

效果圖

效果圖1
效果圖2

思路

當(dāng)一個listView在屏幕上顯示的時候敦迄,它上面(屏幕上面)發(fā)生的各種事件恋追,我們是可以捕捉到的,我們只需要判斷一下是不是我們需要的事件罚屋,如果是的話苦囱,就產(chǎn)生反饋,對事件進(jìn)行處理沿后,否則就不處理即可沿彭。
當(dāng)我們發(fā)現(xiàn)用戶是在一個item上面產(chǎn)生了滑動事件,并且是從右向左滑尖滚,并且滿足我們對有效滑動長度的定義的話,那么這次事件我們就判斷是有效的瞧柔,我們就計算到相應(yīng)的位置漆弄,并且產(chǎn)生相應(yīng)的刪除的按鈕就可以了。
當(dāng)我們發(fā)現(xiàn)用戶的單擊事件的時候造锅,我們就讓刪除的按鈕消失就可以了撼唾。

實現(xiàn)思路來自于:鴻洋的博客

實現(xiàn)代碼

/**
 *  Created by linSir 
 *  date at 2017/5/1.
 *  describe: listView,主要是實現(xiàn)可以側(cè)滑刪除
 */

public class MyListView extends ListView {

    private static final String TAG = MyListView.class.getSimpleName();

    private int touchSlop;  //用戶滑動的最小距離
    private boolean isSliding;  //是否相應(yīng)滑動
    private int xDown;  //按下的x坐標(biāo)
    private int yDown;  //按下的y坐標(biāo)
    private int xMove;  //手指移動時x的坐標(biāo)
    private int yMove;  //手指移動是y的坐標(biāo)
    private LayoutInflater mInflater;   //一個layoutInflater
    private PopupWindow mPopupWindow;   //彈出一個用于展示的popupWindow
    private int mPopupWindowHeight;     //該展示的popupWindow的高度
    private int mPopupWindowWidth;      //該展示的popupWindow的寬度

    private TextView delete;    //側(cè)滑后刪除的按鈕
    private DeleteClickListener mListener;  //點(diǎn)擊刪除后回調(diào)的接口
    private View mCurrentView;  //當(dāng)前展示刪除按鈕的view
    private int mCurrentViewPos;    //當(dāng)前展示刪除按鈕的view的位置(下標(biāo))

    /**
     * 該自定義view的構(gòu)造方法
     */
    public MyListView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mInflater = LayoutInflater.from(context);   //一個Inflater
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();    //最小的滑動距離

        View view = mInflater.inflate(R.layout.delete_btn, null);   //找到刪除按鈕的view
        delete = (TextView) view.findViewById(R.id.delete);     //找到刪除按鈕的控件


        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);    //彈出的popupWindow

        mPopupWindow.getContentView().measure(0, 0);    //初始化
        mPopupWindowHeight = mPopupWindow.getContentView().getMeasuredHeight(); //獲取到該view的高度
        mPopupWindowWidth = mPopupWindow.getContentView().getMeasuredWidth();   //獲取到該view的寬度
    }

    /**
     * 觸摸事件的派發(fā)
     */
    @Override public boolean dispatchTouchEvent(MotionEvent ev) {

        int action = ev.getAction();
        int x = (int) ev.getX();
        int y = (int) ev.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN:   //action_down 即點(diǎn)擊事件哥蔚,這個時候需要關(guān)閉popupWindow
                xDown = x;
                yDown = y;

                if (mPopupWindow.isShowing()) {
                    dismissPopWindow();
                    return false;
                }

                mCurrentViewPos = pointToPosition(xDown, yDown);    //根據(jù)x,y坐標(biāo)獲取到自己的下標(biāo)
                View view = getChildAt(mCurrentViewPos - getFirstVisiblePosition());//當(dāng)前可見view的小標(biāo)減去第一個可見的view的下標(biāo)就可以找到當(dāng)前的這個view
                mCurrentView = view;

                break;

            case MotionEvent.ACTION_MOVE:   //當(dāng)發(fā)生移動時間的時候
                xMove = x;
                yMove = y;
                int dx = xMove - xDown;
                int dy = yMove - yDown;

                if (xMove < xDown && Math.abs(dx) > touchSlop && Math.abs(dy) < touchSlop) { //判斷向左滑動倒谷,并且滑動了一定距離
                    isSliding = true;   //滿足這個條件就符合了打開的popupWindow的條件
                }
                break;
        }

        return super.dispatchTouchEvent(ev);

    }


    @Override public boolean onTouchEvent(MotionEvent ev) {

        if (mCurrentView == null) {     //判斷當(dāng)前的view不存在之后,則直接return不進(jìn)行處理這次時間
            return false;
        }

        int action = ev.getAction();

        if (isSliding) {
            switch (action) {
                case MotionEvent.ACTION_MOVE:
                    int[] location = new int[2];
                    mCurrentView.getLocationOnScreen(location);
                    mPopupWindow.update();

                    delete.setHeight(getMeasuredHeight()/getChildCount());   //計算出來每一個條目的高度

                    mPopupWindow.showAtLocation(mCurrentView, Gravity.LEFT | Gravity.TOP,
                            location[0] + mCurrentView.getWidth(), location[1] + mCurrentView.getHeight() / 2
                                    - mPopupWindowHeight );     //設(shè)置顯示的位置

                    delete.setOnClickListener(new OnClickListener() {
                        @Override public void onClick(View view) {
                            if (mListener != null) {
                                mListener.onClickDelete(mCurrentViewPos);
                                mPopupWindow.dismiss();
                            }
                        }
                    });

                    break;

                case MotionEvent.ACTION_UP:
                    isSliding = false;

                    break;
            }


            return true;
        }
        return super.onTouchEvent(ev);

    }


    private void dismissPopWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }

    }


    public void setDelButtonClickListener(DeleteClickListener listener) {
        mListener = listener;
    }

}
/**
 *  Created by linSir 
 *  date at 2017/5/1.
 *  describe: 用于點(diǎn)擊刪除按鈕的回調(diào)     
 */

public interface DeleteClickListener {

    void onClickDelete(int position);

}

//測試用例

public class MainActivity extends AppCompatActivity {

    private MyListView mListView;
    private ArrayAdapter<String> mAdapter;
    private List<String> mDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (MyListView) findViewById(R.id.id_listview);
        mDatas = new ArrayList<String>(Arrays.asList("111", "222", "333", "444", "555", "666",
                "777", "888", "999", "000"));
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDatas);
        mListView.setAdapter(mAdapter);

        mListView.setDelButtonClickListener(new DeleteClickListener() {
            @Override public void onClickDelete(int position) {
                Toast.makeText(MainActivity.this, position + " : " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
                mAdapter.remove(mAdapter.getItem(position));

            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, position + " : " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
//主界面布局文件

<?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"
    >

  <com.dotengine.linsir.myrecyclerview.MyListView
      android:id="@+id/id_listview"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">


  </com.dotengine.linsir.myrecyclerview.MyListView>

</LinearLayout>

//刪除按鈕的布局

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

    <TextView
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除"
        android:textSize="18sp"
        android:gravity="center"
        android:textColor="#FFF"
        android:background="#b4f72626"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        />

</LinearLayout>


以上便是這次分享的自定義view糙箍,最近一直在看自定義view渤愁,還有事件傳遞機(jī)制這里,也寫了很多測試程序深夯,有空的時候會分享出來的~然后再強(qiáng)調(diào)一下抖格,本文的全部思路來自于張鴻洋的博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末咕晋,一起剝皮案震驚了整個濱河市雹拄,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌掌呜,老刑警劉巖滓玖,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異质蕉,居然都是意外死亡势篡,警方通過查閱死者的電腦和手機(jī)翩肌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來殊霞,“玉大人摧阅,你說我怎么就攤上這事”炼祝” “怎么了棒卷?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長祝钢。 經(jīng)常有香客問我比规,道長,這世上最難降的妖魔是什么拦英? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任蜒什,我火速辦了婚禮,結(jié)果婚禮上疤估,老公的妹妹穿的比我還像新娘灾常。我一直安慰自己,他們只是感情好铃拇,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布钞瀑。 她就那樣靜靜地躺著,像睡著了一般慷荔。 火紅的嫁衣襯著肌膚如雪雕什。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天显晶,我揣著相機(jī)與錄音贷岸,去河邊找鬼。 笑死磷雇,一個胖子當(dāng)著我的面吹牛偿警,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播倦春,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼户敬,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了睁本?” 一聲冷哼從身側(cè)響起尿庐,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎呢堰,沒想到半個月后抄瑟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年皮假,在試婚紗的時候發(fā)現(xiàn)自己被綠了鞋拟。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡惹资,死狀恐怖贺纲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情褪测,我是刑警寧澤猴誊,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站侮措,受9級特大地震影響懈叹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜分扎,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一澄成、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧畏吓,春花似錦墨状、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至巴粪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間粥谬,已是汗流浹背肛根。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留漏策,地道東北人派哲。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓,卻偏偏與公主長得像掺喻,于是被迫代替她去往敵國和親芭届。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,652評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,085評論 25 707
  • 今天是盛世贏家36期凝聚力員工班接放學(xué),現(xiàn)場飽滿的激情讓我們所有人驚呆了即硼!伙伴們?nèi)绱丝蓯厶悠麄冇眯牡臏?zhǔn)備團(tuán)隊...
    落子無悔ss閱讀 217評論 0 0
  • 一段感情結(jié)束了,你說要敬往事一杯酒只酥。干了再也不回頭褥实,可當(dāng)你醉到黃昏獨(dú)自愁呀狼,如果那人伸出手,你依然愿意跟她走损离。 ...
    未凡塵閱讀 574評論 10 4