在不使用butterknife和Databinding的情况下在android中的Activity中创建Instances的最佳方法

Kum*_*mar 0 android butterknife

我曾经使用过两种在android活动中创建实例的方法.哪一种方法更好,方法1或方法2.

方法1:

//Global instance

    Button btn;

    //Inside Oncreate

    btn = (Button)findViewById(R.id.btn);

    //some other Place 
    btn.setVisibility(View.VISIBLE);  
    btn.setText("Hai");
Run Code Online (Sandbox Code Playgroud)

方法2: //在需要它的地方

((Button)findViewById(R.id.btn)).setVisibility(View.VISIBLE);

((Button)findViewById(R.id.btn)).setText("Hai");
Run Code Online (Sandbox Code Playgroud)

不需要ButterknifeData Binding.

小智 9

方法#1的性能优于另一方法,因为您只执行findViewByID一次方法.此方法负责在父布局的层次结构中搜索视图.当Activity被销毁时,垃圾收集器将释放按钮实例的内存.