Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

SwipeListView 實作:打造類 QQ 的滑動側邊操作列表

編輯:關於 Android 程式設計

左右滑動列表項、露出背後的操作按鈕,這種互動從 QQ 之後幾乎成了清單的標準語彙。自己從 ListView 的 onTouch 刻一套並不划算,社群已有成熟方案:47deg 的 SwipeListView。

先看要達成的效果:

一、依賴準備

• SwipeListView:https://github.com/47deg/android-swipelistview
• NineOldAndroids:https://github.com/JakeWharton/NineOldAndroids(SwipeListView 的依賴,用來在低版本上補償動畫 API)

兩者都可以直接把原始碼複製進專案,也可以當作 Library 專案引用。本範例統一採用後者。

二、主版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:swipe="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.fortysevendeg.swipelistview.SwipeListView
        android:id="@+id/example_lv_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:listSelector="#00000000"
        swipe:swipeActionLeft="dismiss"
        swipe:swipeActionRight="reveal"
        swipe:swipeAnimationTime="0"
        swipe:swipeBackView="@+id/back"
        swipe:swipeCloseAllItemsWhenMoveList="true"
        swipe:swipeFrontView="@+id/front"
        swipe:swipeMode="both"
        swipe:swipeOffsetLeft="0dp"
        swipe:swipeOffsetRight="0dp"
        swipe:swipeOpenOnLongPress="false" />
</RelativeLayout>

幾個容易混淆的屬性說明:

• swipeActionLeft/swipeActionRight:滑動時的行為。dismiss 代表滑開即刪除該項;reveal 代表滑開後露出背面的操作區。
• swipeBackView:背面(滑開後才看得到)那層配置的 id,必須與項目配置中的 id 對應。
• swipeFrontView:正面(平常看到的那層)配置的 id。
• swipeCloseAllItemsWhenMoveList:捲動列表時是否自動收起已展開的項,設 true 體驗較好。
• swipeMode:both 可左右滑,left/right 限制單一方向。
• swipeOffsetLeft/swipeOffsetRight:滑出的偏移量,實務上多改在程式碼中依螢幕寬度比例設定,較容易適配不同解析度。
• swipeOpenOnLongPress:長按是否展開,一般設 false。

三、項目配置:前後兩層重疊

用 FrameLayout 讓兩層疊在一起,先加入的是背面,後加入的是正面。

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- 背面:滑開後才看到的操作區 -->
    <LinearLayout
        android:id="@+id/back"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#eee"
        android:tag="back"
        android:orientation="horizontal">

        <Button
            android:id="@+id/example_row_b_action_2"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:text="刪除" />

        <Button
            android:id="@+id/example_row_b_action_3"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:text="編輯" />
    </LinearLayout>

    <!-- 正面:平常顯示的內容 -->
    <RelativeLayout
        android:id="@+id/front"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#ffffff"
        android:tag="front">

        <TextView
            android:id="@+id/example_row_tv_title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textSize="18sp" />
    </RelativeLayout>
</FrameLayout>

四、Activity

public class MainActivity extends Activity {

    private SwipeListView mSwipeListView;
    private SwipeAdapter mAdapter;
    public static int deviceWidth;
    private List<String> testData;

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

        mSwipeListView = (SwipeListView) findViewById(R.id.example_lv_list);
        testData = getTestData();
        mAdapter = new SwipeAdapter(this, R.layout.package_row, testData, mSwipeListView);
        deviceWidth = getResources().getDisplayMetrics().widthPixels;

        mSwipeListView.setAdapter(mAdapter);
        mSwipeListView.setSwipeListViewListener(new TestBaseSwipeListViewListener());
        reload();
    }

    private List<String> getTestData() {
        String[] obj = {"紅樓夢", "西游記", "水浒傳", "管錐編", "宋詩選注", "三國演義", "Android開發高級編程"};
        return new ArrayList<>(Arrays.asList(obj));
    }

    private void reload() {
        // 偏移量依螢幕寬度比例設定,避免在不同解析度上比例失衡
        mSwipeListView.setOffsetLeft(deviceWidth * 1 / 3);
        mSwipeListView.setOffsetRight(deviceWidth * 1 / 3);
        mSwipeListView.setAnimationTime(30);
        mSwipeListView.setSwipeOpenOnLongPress(false);
    }

    class TestBaseSwipeListViewListener extends BaseSwipeListViewListener {

        @Override
        public void onClickFrontView(int position) {
            super.onClickFrontView(position);
            Toast.makeText(getApplicationContext(), testData.get(position), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDismiss(int[] reverseSortedPositions) {
            for (int position : reverseSortedPositions) {
                testData.remove(position);
            }
            mAdapter.notifyDataSetChanged();
        }
    }
}

注意 onDismiss 傳回的是「由後往前排序」的位置陣列,正是為了讓你能安全地在迴圈中逐一 remove 而不影響尚未處理的索引。

五、Adapter

public class SwipeAdapter extends ArrayAdapter<String> {

    private LayoutInflater mInflater;
    private List<String> objects;
    private SwipeListView mSwipeListView;

    public SwipeAdapter(Context context, int textViewResourceId,
                        List<String> objects, SwipeListView swipeListView) {
        super(context, textViewResourceId, objects);
        this.objects = objects;
        this.mSwipeListView = swipeListView;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.package_row, parent, false);
            holder = new ViewHolder();
            holder.mFrontText  = convertView.findViewById(R.id.example_row_tv_title);
            holder.mBackDelete = convertView.findViewById(R.id.example_row_b_action_2);
            holder.mBackEdit   = convertView.findViewById(R.id.example_row_b_action_3);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.mBackDelete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mSwipeListView.closeAnimate(position);  // 先收起動畫
                mSwipeListView.dismiss(position);       // 再觸發刪除
            }
        });

        holder.mFrontText.setText(getItem(position));
        return convertView;
    }

    static class ViewHolder {
        TextView mFrontText;
        Button mBackEdit, mBackDelete;
    }
}

六、實作要點回顧

• 前后兩層用 FrameLayout 疊放,id 必須與 XML 上的 swipeFrontView/swipeBackView 對應。
• 偏移量用螢幕寬度的比例計算,比寫死 dp 更能適配各種解析度。
• 刪除時先 closeAnimate 再 dismiss,避免動畫相互打架。
• 記得在 onDismiss 中呼叫 notifyDataSetChanged,否則清單不會更新。
• 若列表項本身還有手勢衝突(例如橫向滑動的 Gallery 或自訂 ViewPager),可能需要處理事件攔截。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved