Android Adapter 单选

在 Android 开发中,Adapter 是一个重要的组件,用于将数据和 UI 进行绑定。在列表、网格和瀑布流等常见的 UI 控件中,都需要使用 Adapter 来展示数据。本文将介绍如何使用 Android Adapter 实现单选功能。

Adapter 概述

在 Android 中,Adapter 是一个用于提供数据的桥梁,将数据与 UI 控件进行绑定。常见的 Adapter 有 ArrayAdapter、BaseAdapter、RecyclerView.Adapter 等。它们都实现了 Adapter 接口,并且提供了一些方法用于获取数据长度、获取某个位置的数据项等。

单选功能实现

实现 Adapter 的单选功能,可以通过以下步骤进行:

  1. 在 Adapter 中添加一个变量用于记录选中的位置;
  2. 在 Adapter 的 getView() 方法中根据选中的位置来设置 UI 控件的状态;
  3. 在 UI 控件的点击事件中更新选中位置,并通知 Adapter 数据发生变化。

下面是一个使用 ArrayAdapter 实现单选功能的示例代码:

public class SingleChoiceAdapter extends ArrayAdapter<String> {

    private int selectedItem = -1;

    public SingleChoiceAdapter(Context context, List<String> items) {
        super(context, 0, items);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_single_choice, parent, false);
        }

        final TextView textView = convertView.findViewById(R.id.text_view);
        textView.setText(getItem(position));

        if (position == selectedItem) {
            textView.setBackgroundColor(Color.BLUE);
        } else {
            textView.setBackgroundColor(Color.WHITE);
        }

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedItem = position;
                notifyDataSetChanged();
            }
        });

        return convertView;
    }
}

在上述代码中,我们自定义了一个 SingleChoiceAdapter 继承自 ArrayAdapter,在 getView() 方法中根据选中的位置来设置 TextView 的背景色。当用户点击某个 TextView 时,我们更新选中位置并调用 notifyDataSetChanged() 方法通知 Adapter 数据发生变化。

序列图

下面是一个使用 Mermaid 语法绘制的 Adapter 单选的序列图:

sequenceDiagram
    participant User
    participant Adapter
    participant TextView

    User->>Adapter: 点击 TextView
    Adapter-->>Adapter: 更新选中位置
    Adapter-->>Adapter: 调用 notifyDataSetChanged()
    Adapter->>TextView: 设置背景色
    Note right of TextView: 根据选中的位置来设置背景色

如上所示,用户点击 TextView 触发事件后,Adapter 更新选中位置并调用 notifyDataSetChanged() 方法,然后根据选中的位置来设置 TextView 的背景色。

类图

下面是一个使用 Mermaid 语法绘制的 Adapter 单选的类图:

classDiagram
    class ArrayAdapter {
        +ArrayAdapter(Context, int, List<T>)
        +getView(int, View, ViewGroup): View
    }

    class SingleChoiceAdapter {
        -selectedItem: int
        +SingleChoiceAdapter(Context, List<String>)
        +getView(int, View, ViewGroup): View
    }

    ArrayAdapter <|-- SingleChoiceAdapter

如上所示,SingleChoiceAdapter 继承自 ArrayAdapter。

总结

使用 Adapter 实现单选功能是 Android 开发中常见的需求。通过在 Adapter 中记录选中的位置,并在 getView() 方法中根据选中的位置来设置 UI 控件的状态,可以很容易地实现单选功能。希望本文对你理解和使用 Android Adapter 有所帮助。

参考资料:

  • [Android Developers - Adapter](
  • [Android Developers - ArrayAdapter](