andorid jar/库源码解析之Butterknife

目录:andorid jar/库源码解析 html

Butterknife:

  做用:

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

  栗子:

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);

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

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

  二、获得类,调用他的构造函数,函数中经过findViewById,来进行绑定(因为A+_ViewBinding是生成的类,该类已知了全部须要绑定的控件,因此顺序处理了。)this

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

  四、到这里。全部操做就关联上了。code

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

  

  引入:

    // 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'
相关文章
相关标签/搜索