andorid jar/库源码解析之Butterknife

目录:andorid jar/库源码解析 

Butterknife:

  作用:

    用于初始化界面控件,控件方法,通过注释进行绑定控件和控件方法

  栗子:

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.btnTest1)
    Button btnTest1;

    @BindView(R.id.btnTest2)
    Button btnTest2;

    @BindView(R.id.lblMsg)
    TextView lblMsg;

    @BindView(R.id.txtMsg)
    EditText txtMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
    }

    @OnClick(R.id.btnTest1) void test1(){
        Toast.makeText(this, txtMsg.getText().toString(), Toast.LENGTH_LONG).show();
    }

    @OnClick(R.id.btnTest2) void test2(){
        String msg = "test2222222222";
        lblMsg.setText(msg);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

  源码解读:

ButterKnife.bind(this);

  绑定界面元素和方法的关联。

  1、传入当前对象,得到当前对象的类名A,查找A+‘_ViewBinding’组成的类名的,类的构造函数,参数是A类对象和View

  2、得到类,调用他的构造函数,函数中通过findViewById,来进行绑定(由于A+_ViewBinding是生成的类,该类已知了所有需要绑定的控件,所以顺序处理了。)

  3、对于事件方法,则创建了已定义的兼容性的子类,进行调用处理。

  4、到这里。所有操作就关联上了。

  自动生成了,_ViewBinding类,用于关联

  

  源码:https://github.com/JakeWharton/butterknife

  引入:

    // androidx
    implementation 'com.jakewharton:butterknife:10.0.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'


    // android.support.v4.content
    // implementation 'com.jakewharton:butterknife:8.8.1'
    // annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

 

posted @ 2020-04-24 17:49  Supper_litt  阅读(338)  评论(0编辑  收藏  举报