问题
在有赞实习,他们的代码中使用了很多butterknife的相关操作,于是实践一下,简单实现自己想象中的绑定与点击
思路
BindView简化findViewById(R.id.xxx)
BindClick简化setOnClickListener(this);
0.绑定时两个参数:Object host, View view。
1.遍历宿主中的全部Field,为设置了BindView注解的添加findViewById
2.查看宿主的BindClick,如果有,为BindClick中的变量设置setOnClickListener
效果
image.png
文件结构
image.png
使用代码
MainActivity.java
@BindClick(ids = { R.id.btnOne, R.id.btnTwo, R.id.btnThree })public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @BindView(id = R.id.txt) public TextView txt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CopyButterKnife.bind(this, getWindow().getDecorView()); init(); } private void init() { txt.setText("hello copybutterknife"); getSupportFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit(); } public void onClick(View view){ int id = view.getId(); if (id == R.id.btnOne){ txt.setText("activity buttonOne Click"); } if (id == R.id.btnTwo){ txt.setText("activity buttonTwo Click"); } if (id == R.id.btnThree){ txt.setText("hello copybutterknife"); } } }
MainFragment.java
@BindClick(ids = { R.id.btnOne, R.id.btnTwo, R.id.btnThree })public class MainFragment extends Fragment implements View.OnClickListener { private View root; @BindView(id = R.id.txt) public TextView txt; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_main, null); CopyButterKnife.bind(this, root); init(); return root; } private void init(){ txt.setText("hello world"); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btnOne){ txt.setText("fragment one click"); } else if (id == R.id.btnTwo){ txt.setText("fragment two click"); } else if (id == R.id.btnThree){ txt.setText("hello world"); } } }
工具代码
BindClick.java
@Retention(RetentionPolicy.RUNTIME) public @interface BindClick { int[] ids(); }
BindView.java
@Retention(RetentionPolicy.RUNTIME)public @interface BindView { int id(); }
CopyButterKnife.java
public class CopyButterKnife { public static void bind(Object host, View view) { Field[] fields = host.getClass().getFields(); for (Field field : fields) { BindView bindView = field.getAnnotation(BindView.class); if (bindView != null) { try { field.set(host, view.findViewById(bindView.id())); } catch (IllegalAccessException e) { e.printStackTrace(); } } } BindClick bindClick = host.getClass().getAnnotation(BndClick.class); if (bindClick != null) { int[] ids = bindClick.ids(); for (int id : ids) { view.findViewById(id).setOnClickListener((View.OnClickListener) host); } } } }
作者:pgydbh
链接:https://www.jianshu.com/p/8a25cdd734bc