19
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

新しく追加されるViewTreeLifecycleOwnerについて

Posted at

プルリクをなんとなく見ていて発見して面白そうだったので書いてみました。 (まだ未リリースっぽいです)
https://android-review.googlesource.com/q/project:platform/frameworks/support+viewtreelifecycleowner

ViewTreeLifecycleOwnerとは

ViewからLifecycleOwnerを取得できる仕組みです。
例えば以下のようにすることでLifecycleOwnerを取得できます。このLifecycleOwnerは直近のFragmentやActivityを取得できる形になります。
個人的にはCustomViewなどでライフサイクルを取得するのに便利なのではと思っています。

view.findViewTreeLifecycleOwner()

どのように実現されるのか?

ComponentActivity内

ルートのViewであるDecorViewに対してActivityをセットしています

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        // Set the VTLO before setting the content view so that the inflation process
        // and attach listeners will see it already present
        ViewTreeLifecycleOwner.set(getWindow().getDecorView(), this);
        super.setContentView(layoutResID);
    }

Fragment内

Fragmentでも同様にセットしています。

    void performCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
...
            ViewTreeLifecycleOwner.set(mView, mViewLifecycleOwner);

ViewTreeLifecycleOwner

ViewTreeLifecycleOwnerではただ単純にタグに入れるだけです

    public static void set(@NonNull View view, @Nullable LifecycleOwner lifecycleOwner) {
        view.setTag(R.id.view_tree_lifecycle_owner, lifecycleOwner);
    }

どのようにLifecycleOwnerを取得するのか?
以下のように単純にparentをたどることで取得できるようです。

    public static LifecycleOwner get(@NonNull View view) {
        LifecycleOwner found = (LifecycleOwner) view.getTag(R.id.view_tree_lifecycle_owner);
        if (found != null) return found;
        ViewParent parent = view.getParent();
        while (found == null && parent instanceof View) {
            final View parentView = (View) parent;
            found = (LifecycleOwner) parentView.getTag(R.id.view_tree_lifecycle_owner);
            parent = parentView.getParent();
        }
        return found;
    }
}
19
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?