Android----模仿ButterKnife的簡單實踐
問題
在有贊實習,他們的程式碼中使用了很多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); } } } }
demo
ofollow,noindex">https://github.com/pgyCode/CopyButterKnife