> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/android/10.3.-gan-diao-findbyid.md).

# 10.3.干掉findById

在开始之前，假设存在某个布局文件，名称为 `result_profile.xml`：

```markup
<LinearLayout ... >
        <TextView android:id="@+id/name" />
        <ImageView android:cropToPadding="true" />
        <Button android:id="@+id/button" android:background="@drawable/rounded_button" />
</LinearLayout>
```

现在你要在java文件中查找该布局文件中的view。

## 你是否仍然使用`findViewById`查找view？

```java
class ExampleActivity extends Activity {
  private TextView tv;
  private Button btn;

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

  private void initView() {
      tv = findViewById(R.id.name);
      btn = findViewById(R.id.button);
  }
}
```

反复的findViewById有没有觉得很累，有没有更优雅的方式？

## 使用Butter Knife更优雅的查找view

Butter Knife是一个专注于Android系统的View注入框架，通过在字段上使用`@BindView`代替`indViewById`调用。

```java
class ExampleActivity extends Activity {
  @BindView(R.id.name) TextView tv;
  @BindView(R.id.button) private Button btn;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result_profile);
    ButterKnife.bind(this);
  }
}
```

当然，Butter Knife的功能不仅仅如此哦！它还可以

* Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
* Eliminate anonymous inner-classes for listeners by annotating methods with `@OnClick` and others.
* Eliminate resource lookups by using resource annotations on fields.

集成方式，请见[butterknife](https://github.com/JakeWharton/butterknife)

## view binding

若你现在访问[Butter Knife](https://github.com/JakeWharton/butterknife)，你会发现Butter Knife目前已弃用，它推荐你使用view binding。View Binding是什么呢？

View Binding是Android Studio 3.6推出的新特性，目的是为了替代`findViewById`（内部实现还是使用findViewById）。

```java
class ExampleActivity extends Activity {
    private ResultProfileBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ResultProfileBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
    }

    ...
    binding.getName().setText(viewModel.getName());
    binding.button.setOnClickListener(new View.OnClickListener() {
        viewModel.userClicked()
    });

}
```

由于View Binding是Android Studio 3.6推出的新特性，升级Android Studio 至3.6及以上版本即可直接使用。

更多资料请见[官方文档](https://links.jianshu.com/go?to=https%3A%2F%2Fdeveloper.android.google.cn%2Ftopic%2Flibraries%2Fview-binding)
