1. 程式人生 > >Android 實現ListView item的左滑(右滑)監聽事件 swipemenulistview

Android 實現ListView item的左滑(右滑)監聽事件 swipemenulistview

這篇文章將會介紹我是如何學習item的左滑監聽事件設定的,首先我們先新增依賴:
compile ‘com.baoyz.swipemenulistview:library:1.3.+’
可以看到,我們是藉助大神所寫的swipemenulistView這個空間來實現我們的左滑事件的。匯入之後呢,我們就可以開始我們的專案了。

首先和往常寫listView寫好我們的佈局檔案,但是以前所有的listView控制元件就需要我們使用這一款新的控制元件代替了。
main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:swipe="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.administrator.learnlistviewmenu.MainActivity">
<com.baoyz.swipemenulistview.SwipeMenuListView
android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" >
</com.baoyz.swipemenulistview.SwipeMenuListView> </RelativeLayout>

接下來是我們的item佈局檔案:
list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/nameTextView"
    android:textSize="20sp"
    android:layout_width="match_parent"
    android:layout_height="40dp" />
    <TextView
        android:id="@+id/ageTextView"
        android:textSize="15sp"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
</LinearLayout>

然後程式碼部分,還是需要我們自己去建立介面卡,以及寫一個數據類來存放需要顯示的資料。這和以前我們寫listView的思想一樣,接下來我們直接放程式碼吧。
資料類Person:

public class Person {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
    public Person(){

    }
    String name ;
    String age;
}

item 的AppView類:

public class AppView extends LinearLayout {
    private Context context;
    private TextView nameTextView;
    private TextView ageTextView;

    public AppView(Context context) {
        super(context);
        this .context = context;
        init(context);
    }
    public void init(Context context){
        this.context = context;
        View view = LayoutInflater.from(this.context).inflate(R.layout.listview_item,null);
        nameTextView = (TextView) view .findViewById(R.id.nameTextView);
        ageTextView = (TextView) view.findViewById(R.id.ageTextView);
        addView(view);
    }
    public void updateView(Person person){
        nameTextView.setText(person.getName());
        ageTextView.setText(person.getAge());
    }
}

Adapter:

public class ListViewAdapter extends BaseAdapter {
   private Context context;
    private List<Person> infos;
    public ListViewAdapter(Context context, List<Person> infos){
            this.context =context;
            this.infos=infos;
    }
    public int getCount() {
        return infos.size();
    }

    @Override
    public Object getItem(int i) {
        return infos.get(i);
    }

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



    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(infos==null){
            return null;
        }
        if(view==null){
            AppView appView = new AppView(context);
            appView.updateView(infos.get(i));
            view = appView;
            view.setTag(appView);
        }else{
            view = (View) view.getTag();
        }
        return view;
    }

}

接下來就是比較重要,也是比較關鍵的MainActivity類了.

package com.example.administrator.learnlistviewmenu;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    List<Person> infos = new ArrayList<Person>();
    SwipeMenuCreator creator = new SwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
        //create open item
            SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
            //set backg
            openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                    0xCE)));
            openItem.setWidth(dip2px(MainActivity.this,90));
            openItem.setTitle("Open");
            openItem.setTitleSize(18);
            openItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(openItem);
            SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getApplicationContext());
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            // set item width
            deleteItem.setWidth(dip2px(MainActivity.this,90));
            // set a icon
            deleteItem.setIcon(R.mipmap.ic_launcher);
            // add to menu
            menu.addMenuItem(deleteItem);
        }
    };
    SwipeMenuListView listView;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loadDada();
        ListViewAdapter adapter = new ListViewAdapter(this,infos);
        listView = (SwipeMenuListView) findViewById(R.id.listView);
        listView.setMenuCreator(creator);
        listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        listView.setAdapter(adapter);
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index){
                    case 0:
                        Toast.makeText(MainActivity.this, "open", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "delete", Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
    }
    public void loadDada(){
        for(int i = 0 ;i<=20;i++){
            Person x = new Person();
            x.setName("my name is "+i);
            x.setAge("my age is "+i);
            infos.add(x);
        }
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px2dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     *根據裝置資訊獲取當前解析度下指定單位對應的畫素大小;
     * px,dip,sp -> px
     */
    public float getRawSize(Context c, int unit, float size) {
        Resources r;
        if (c == null){
            r = Resources.getSystem();
        }else{
            r = c.getResources();
        }
        return TypedValue.applyDimension(unit, size, r.getDisplayMetrics());
    }
}

這裡面可以看到,我們的控制元件設定屬性:

SwipeMenuCreator creator = new SwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
        //create open item
            SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
            //set backg
            openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                    0xCE)));
            openItem.setWidth(dip2px(MainActivity.this,90));
            openItem.setTitle("Open");
            openItem.setTitleSize(18);
            openItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(openItem);
            SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getApplicationContext());
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            // set item width
            deleteItem.setWidth(dip2px(MainActivity.this,90));
            // set a icon
            deleteItem.setIcon(R.mipmap.ic_launcher);
            // add to menu
            menu.addMenuItem(deleteItem);
        }
    };

這一款程式碼就是我們設定的屬性,說白了就是設定的左滑後顯示的item的屬性,這裡我們可以自己去設定他的圖片背景,大小以及title,這裡設定好之後,在後面新增監聽後的方法中就可以去寫相應的觸發事件了.

 listView.setMenuCreator(creator);
        listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
        listView.setAdapter(adapter);
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index){
                    case 0:
                        Toast.makeText(MainActivity.this, "open", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(MainActivity.this, "delete", Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
    }

在使用的時候,我們必須傳入最開始設定好的creator然後選擇Direction,然後新增監聽之後,我們就是通過switch判斷index來,判斷點選的具體的左滑item功能按鈕.完成相應的方法。

這大概就是swipemenulistview的初使用了,本片文章只是記錄學習過程,有很多不規範和有問題的寫法的話。請大神勿噴啊