定义
适配器模式把一个类的接口变换成客户端所期待的另一个接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作
使用场景
- 系统需要使用现有的类,而此类的接口不符合系统的需要,即接口不支持
- 想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作
- 需要一个统一的输出接口,而输入端的类型不可预知
模式组成
- Target 目标角色,也就是所期待得到的接口
- Adaptee 现在需要适配的接口
- adapter 适配器角色
是适配器模式的核心,适配器把源接口转换成目标接口。承担这一角色不可能是接口,而必须是具体类
适配器模式种类
适配器模式可以分为2种
-
类适配器模式
类适配器模式是通过实现 Target 接口以及继承 Adaptee 类来实现接口转换
-
对象适配器模式
对象适配器模式不是使用继承关系连接到 Adaptee 类,而是使用代理关系连接到 Adaptee 类
简单实现
实现一个简单圆形菜单功能
public class MenuItem {
public int imageId;
public String title;
public MenuItem(int imageId, String title) {
this.imageId = imageId;
this.title = title;
}
}
MenuItem 为菜单内容实体类,用于存储菜单项图标和文本信息
public class CircleMenuLayout extends ViewGroup {
// 圆形直径
private int mRadius;
// 容器内 child item 的默认尺寸
private static final float RADIO_DEFAULT_CHILD_DIMENSION = 1 / 4f;
//容器的内边距
private static final float RADIO_PADDING_LAYOUT = 1 / 12f;
private float mPadding;
//布局时的开始角度
private double mStartAngel = 0;
private Adapter adapter;
private OnMenuItemClickListener onItemClickListener;
public CircleMenuLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setAdapter(Adapter adapter) {
this.adapter = adapter;
}
public void setOnItemClickListener(OnMenuItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureSelf(widthMeasureSpec, heightMeasureSpec);
measureChildViews();
}
private void measureSelf(int widthMeasureSpec, int heightMeasureSpec) {
int resWidth = 0;
int resHeight = 0;
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
//设置背景图的高度
resWidth = getSuggestedMinimumWidth();
resWidth = resWidth == 0 ? getDefaultWidth() : resWidth;
//如果未设置背景图片,则设置为屏幕宽高的默认值
resHeight = getSuggestedMinimumHeight();
resHeight = resHeight == 0 ? getDefaultWidth() : resHeight;
} else {
resWidth = resHeight = Math.min(width, height);
}
setMeasuredDimension(resWidth, resHeight);
}
private void measureChildViews() {
//获得半径
mRadius = Math.max(getMeasuredWidth(), getMeasuredHeight());
final int count = getChildCount();
int childSize = (int) (mRadius * RADIO_DEFAULT_CHILD_DIMENSION);
int childMode = MeasureSpec.EXACTLY;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
int makeMeasureSpec = MeasureSpec.makeMeasureSpec(childSize, childMode);
child.measure(makeMeasureSpec, makeMeasureSpec);
}
mPadding = RADIO_PADDING_LAYOUT * mRadius;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int childCount = getChildCount();
int left, top;
int itemWidth = (int) (mRadius * RADIO_DEFAULT_CHILD_DIMENSION);
//计算 item 的布局占用角度
float angelDelay = 360 / childCount;
for (int i = 0; i < adapter.getCount(); i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
mStartAngel %= 360;
//计算中心点到 menu item 的距离
float distancefromCenter = mRadius / 2f - itemWidth / 2 - mPadding;
//menu item 中心点的 left 坐标
left = (int) (mRadius / 2 + Math.round(distancefromCenter * Math.cos(Math.toRadians(mStartAngel)) - 1 / 2f * itemWidth));
// menu item 的中心点的 纵坐标
top = (int) (mRadius / 2 + Math.round(distancefromCenter * Math.sin(Math.toRadians(mStartAngel)) - 1 / 2f * itemWidth));
//layout child item
child.layout(left, top, left + itemWidth, top + itemWidth);
// 叠加尺寸, 调整初始角度
mStartAngel += angelDelay;
}
}
@Override
protected void onAttachedToWindow() {
if (adapter != null) {
buildMenuItems();
}
super.onAttachedToWindow();
}
private void buildMenuItems() {
for (int i = 0; i < adapter.getCount(); i++) {
final View viewItem = adapter.getView(i, null, this);
final int position = i;
viewItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(viewItem, position);
}
}
});
addView(viewItem);
}
}
/**
* 获得该 layout 的尺寸
*
* @return
*/
public int getDefaultWidth() {
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return Math.min(outMetrics.widthPixels, outMetrics.heightPixels);
}
public interface OnMenuItemClickListener {
void onItemClick(View view, int position);
}
}
CircleMenuLayout 为自定义圆形菜单View,该类关联了一个Adapter 对象 adapter,Adapter是ListView、RecyclerView等View的共同父类,也就是说说适用于ListView或者RecyclerView的Adapter数据同样也适用于该View。
CircleMenuLayout在 onAttachedToWindow 函数中调用 Adapter 的 getCount 函数获取菜单项的数目,然后通过 getView 函数获取每个 View,最后将这些 View 添加到圆形菜单中
整个过程中,CircleMenuLayout 不知道菜单项的具体布局和所以成员,对 CircleMenuLayout 来说不管菜单项怎么变化,它终将是一个 view ,菜单项的具体 view 是什么样子,交由 Adapter 去实现
public class CircleMenuAdapter extends BaseAdapter {
List<MenuItem> mMenuItems = new ArrayList<>();
public CircleMenuAdapter(List<MenuItem> mMenuItems) {
this.mMenuItems = mMenuItems;
}
@Override
public int getCount() {
return mMenuItems.size();
}
@Override
public MenuItem getItem(int position) {
if (position > mMenuItems.size()) {
}
return mMenuItems.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(parent.getContext());
View itemView = mInflater.inflate(R.layout.circle_menu_item, parent, false);
initMenuItem(itemView, position);
return itemView;
}
/**
* 初始化菜单项布局
*
* @param itemView 菜单view
* @param position 菜单项所在位置
*/
private void initMenuItem(View itemView, int position) {
MenuItem t = getItem(position);
TextView tv = itemView.findViewById(R.id.circle_tv);
ImageView iv = itemView.findViewById(R.id.circle_iv);
iv.setImageResource(t.imageId);
tv.setText(t.title);
}
}
CircleMenuAdapter 为getView中加载每一项菜单的布局文件,并且绑定数据等。最终将菜单 View 返回,然后这个 View 就会被添加到 CircleMenuLayout 中。
public class TestAdapterActy extends AppCompatActivity {
private CircleMenuLayout mLayout;
private List<MenuItem> mMenuItems = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testadapter_acty);
mockMenuItems();
mLayout = findViewById(R.id.lv);
CircleMenuAdapter adapter = new CircleMenuAdapter(mMenuItems);
mLayout.setOnItemClickListener(new CircleMenuLayout.OnMenuItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(TestAdapterActy.this, mMenuItems.get(position).title, Toast.LENGTH_SHORT).show();
}
});
mLayout.setAdapter(adapter);
}
private List<MenuItem> mockMenuItems() {
MenuItem item0 = new MenuItem(R.mipmap.ic_launcher_round, "动漫");
MenuItem item1 = new MenuItem(R.mipmap.ic_launcher, "电视剧");
MenuItem item2 = new MenuItem(R.mipmap.ic_launcher_round, "电影");
MenuItem item3 = new MenuItem(R.mipmap.ic_launcher, "音乐");
MenuItem item4 = new MenuItem(R.mipmap.ic_launcher_round, "综艺");
mMenuItems.add(item0);
mMenuItems.add(item1);
mMenuItems.add(item2);
mMenuItems.add(item3);
mMenuItems.add(item4);
return mMenuItems;
}
}
运行结果如下: