前言
解决多个 view 同时显隐,响应同一点击事件的方法有什么?
- 外部套布局 (缺陷:增加无用布局)
- 给多个 view 设置监听事件,调用同一执行代码(缺陷:代码冗余)
正文
解决方法
使用 ConstraintHelper 特性编写自定义 GroupView
ConstraintHelper 代码很容易看懂,就不多提。核心就是增加了一个自定义属性 constraint_referenced_ids 可以引用的其他 view id,实现“联动”。
演示
源代码
GroupView.java
package com.common.base.view.widget;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintHelper;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
/**
* @author eddiezx
* 统一显隐
* 统一点击事件
*/
public class GroupView extends ConstraintHelper {
/**
* 缓存引用 view
*/
private SparseArray<View> mReferenceViews = new SparseArray<>();
public GroupView(Context context) {
this(context, null);
}
public GroupView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GroupView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
// 不占渲染性能
setVisibility(GONE);
}
@Override
public void setOnClickListener(@Nullable OnClickListener l) {
for (int i = 0; i < this.mCount; ++i) {
int id = this.mIds[i];
View view = mReferenceViews.get(id);
if (view == null) {
view = getRootView().findViewById(id);
mReferenceViews.put(id, view);
}
if (view != null) {
view.setOnClickListener(v -> {
if (l != null) {
l.onClick(GroupView.this);
}
});
}
}
}
@Override
public void setVisibility(int visibility) {
for (int i = 0; i < this.mCount; ++i) {
int id = this.mIds[i];
View view = mReferenceViews.get(id);
if (view == null) {
view = getRootView().findViewById(id);
mReferenceViews.put(id, view);
}
if (view != null) {
view.setVisibility(visibility);
}
}
}
}
使用方法:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<com.eddie.viewdemo.GroupView
android:id="@+id/group_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:constraint_referenced_ids="tv1,tv2" />
<TextView
android:id="@+id/tv1"
style="@style/actvitiy_main_text"
android:text="hello" />
<TextView
android:id="@+id/tv2"
style="@style/actvitiy_main_text"
android:text="world" />
<Button
android:id="@+id/btn_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示" />
</LinearLayout>
配合 ButterKnife 简单食用
@OnClick(R.id.group_view)
fun onClick(view: View) {
when (view.id) {
R.id.group_view -> {
// tv1,tv2 都会调用此方法
Toast.makeText(this, "hello world", Toast.LENGTH_SHORT).show();
groupView.visibility = View.GONE
}
R.id.btn_show -> {
groupView.visibility = View.VISIBLE
}
}
}
总结
- 使用简单
- 减少布局嵌套
- 减少冗余代码,避免维护成本