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

ExpandableListView 可折疊列表與 StackView 棧式視圖用法詳解

編輯:關於 Android 程式設計

這一節介紹兩個帶適配器的控件:ExpandableListView(可折疊列表)與 StackView(棧式視圖)。前者是 QQ 好友分組那類效果的經典實現,後者則能把一組 View 層層堆疊、任意翻換。

一、ExpandableListView 可折疊列表

它是 ListView 的子類,用法相近,但多了一層「分組 → 子項」的結構。

常用 XML 屬性

· android:childDivider:各組內子項之間的分隔條
· android:childIndicator:顯示在子列表旁邊的 Drawable
· android:childIndicatorEnd / Left / Right / Start:子列表指示符的約束位置
· android:groupIndicator:顯示在組列表旁邊的 Drawable
· android:indicatorEnd / Left / Right / Start:組列表指示器的約束位置

三種適配器實現方式

1. 自定義類繼承 BaseExpandableListAdapter
2. 使用 SimpleExpandableListAdapter 包裝兩個 List 集合
3. 使用 SimpleCursorTreeAdapter 把 Cursor 中的資料包裝成樹形結構

下面用第一種方式,最靈活也最常見。

布局檔案

組項 item_group.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_group_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="28dp"
        android:layout_marginTop="10dp"
        android:padding="8dp"
        android:text="張三"
        android:textColor="#000000"
        android:textSize="16sp" />
</LinearLayout>

子項 item_child.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/iv_child_icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_margin="8dp"
        android:padding="2dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_child_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="子節點"
        android:textColor="#330000"
        android:textSize="12sp" />
</LinearLayout>

主布局:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    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">

    <ExpandableListView
        android:id="@+id/ex_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:childDivider="#E02D2F" />
</RelativeLayout>

自定義適配器

需要實現的方法可以分成兩組:一組回答「有多少組、每組多少子項」(getGroupCount、getChildrenCount),一組負責渲染(getGroupView、getChildView)。

public class CustomAdapter extends BaseExpandableListAdapter {
    private List<Group> groupList;
    private List<List<Child>> childList;
    private Context mContext;

    public CustomAdapter(Context mContext, List<Group> groupList,
                         List<List<Child>> childList) {
        this.mContext = mContext;
        this.groupList = groupList;
        this.childList = childList;
    }

    @Override
    public int getGroupCount() {
        return groupList.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return childList.get(i).size();
    }

    @Override
    public Object getGroup(int i) {
        return groupList.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return childList.get(i).get(i1);
    }

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

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        GroupViewHolder holder = null;
        if (view == null) {
            view = LayoutInflater.from(mContext)
                    .inflate(R.layout.item_group, viewGroup, false);
            holder = new GroupViewHolder();
            holder.tv_group_name = (TextView) view.findViewById(R.id.tv_group_name);
            view.setTag(holder);
        } else {
            holder = (GroupViewHolder) view.getTag();
        }
        holder.tv_group_name.setText(groupList.get(i).getGroupName());
        return view;
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        ChildViewHolder holder = null;
        if (view == null) {
            view = LayoutInflater.from(mContext)
                    .inflate(R.layout.item_child, viewGroup, false);
            holder = new ChildViewHolder();
            holder.iv_child_icon = (ImageView) view.findViewById(R.id.iv_child_icon);
            holder.tv_child_name = (TextView) view.findViewById(R.id.tv_child_name);
            view.setTag(holder);
        } else {
            holder = (ChildViewHolder) view.getTag();
        }
        holder.iv_child_icon.setImageResource(R.mipmap.ic_launcher);
        holder.tv_child_name.setText(childList.get(i).get(i1).getChildName());
        return view;
    }

    /**
     * 必須返回 true,否則子項點擊事件不生效
     */
    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    private static class GroupViewHolder {
        TextView tv_group_name;
    }

    private static class ChildViewHolder {
        ImageView iv_child_icon;
        TextView tv_child_name;
    }
}

兩個資料模型類很簡單:

public class Group {
    private String groupName;
    public Group() {}
    public Group(String groupName) { this.groupName = groupName; }
    public String getGroupName() { return groupName; }
    public void setGroupName(String groupName) { this.groupName = groupName; }
}

public class Child {
    private String childName;
    public Child() {}
    public Child(String childName) { this.childName = childName; }
    public String getChildName() { return childName; }
    public void setChildName(String childName) { this.childName = childName; }
}

Activity

public class MainActivity extends AppCompatActivity {

    private List<Group> groupList;
    private List<List<Child>> childList;
    private ExpandableListView ex_list;
    private CustomAdapter customAdapter;

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

        ex_list = (ExpandableListView) findViewById(R.id.ex_list);
        initData();
        customAdapter = new CustomAdapter(this, groupList, childList);
        ex_list.setAdapter(customAdapter);

        // 子項點擊事件
        ex_list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View view,
                                        int i, int i1, long l) {
                Toast.makeText(MainActivity.this,
                        "你點擊的是:" + childList.get(i).get(i1).getChildName(),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void initData() {
        groupList = new ArrayList<>();
        childList = new ArrayList<>();

        groupList.add(new Group("載貨汽車"));
        groupList.add(new Group("越野汽車"));
        groupList.add(new Group("自卸汽車"));
        groupList.add(new Group("專用汽車"));
        groupList.add(new Group("客車"));
        groupList.add(new Group("牽引車"));
        groupList.add(new Group("轎車"));
        groupList.add(new Group("半掛車"));

        List<Child> child1 = new ArrayList<>();
        child1.add(new Child("微型貨車"));
        child1.add(new Child("輕型貨車"));
        child1.add(new Child("中型貨車"));
        child1.add(new Child("重型貨車"));
        childList.add(child1);

        // 其餘分組依此類推……
        List<Child> child2 = new ArrayList<>();
        child2.add(new Child("輕型越野車"));
        child2.add(new Child("中型越野車"));
        childList.add(child2);
    }
}

兩個要點值得記住:ViewHolder + setTag 複用(與 ListView 同理,避免重複 findViewById),以及 isChildSelectable 必須返回 true,否則 setOnChildClickListener 永遠不會觸發——這是新手最常踩的坑。

二、StackView 棧式視圖

StackView 把一組 View 層層堆疊,一次只展示最上面一個,可以通過手勢拖拽或程式調用來翻換。它屬於 API 11 之後引入的 RemoteViews 家族成員(可用於 AppWidget 通知等場景)。

布局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <StackView
        android:id="@+id/sk"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:loopviews="true">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn_previous"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="前一張" />
        </LinearLayout>
    </StackView>

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="後一張" />
</LinearLayout>

android:loopviews="true" 表示循環展示,翻到最後一項會回到第一項。

Activity

public class StackViewActivity extends AppCompatActivity {

    private StackView sk;
    private Button btn_previous, btn_next;
    private int[] mColors = {Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, Color.RED};

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

        sk = (StackView) findViewById(R.id.sk);
        btn_next = (Button) findViewById(R.id.btn_next);
        btn_previous = (Button) findViewById(R.id.btn_previous);

        sk.setAdapter(new ColorAdapter(getApplicationContext(), mColors));

        btn_previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sk.showPrevious();
            }
        });

        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sk.showNext();
            }
        });
    }

    /** 自定義適配器 */
    private class ColorAdapter extends BaseAdapter {
        private Context mContext;
        private int[] mColors;

        public ColorAdapter(Context context, int[] colors) {
            mContext = context;
            mColors = colors;
        }

        @Override
        public int getCount() {
            return mColors == null ? 0 : mColors.length;
        }

        @Override
        public Object getItem(int position) {
            return mColors == null ? null : mColors[position];
        }

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

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(400, 400);
            LinearLayout colorLayout = new LinearLayout(mContext);
            colorLayout.setBackgroundColor(mColors[position]);
            colorLayout.setLayoutParams(lp);
            return colorLayout;
        }
    }
}

StackView 的翻轉動畫是系統內建的,效果比 ListView 這類平面列表更有層次感。除了 showNext() / showPrevious(),它也支持直接用手勢滑動切換,適合做「卡片堆」式的引導頁或圖片瀏覽。

兩個控件的選型建議

· 需要多層級展示、且層級固定為兩層時,ExpandableListView 依然是最直接的選擇;但若層級更深或需要自定義展開動畫,用 RecyclerView + 多種 ItemViewType 自己實現會更可控。
· StackView 適合「元素不多、需要層疊視覺」的場景。它繼承自 AdapterView 體系,因此同樣受 AdapterView 的複用機制約束,getView 中也要注意 ViewHolder 優化。
· 兩者都建議在数据層與視圖層之間加一層 ViewModel,避免像示例那樣把資料硬編碼在 Activity 裡。

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