Help us understand the problem. What is going on with this article?

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

プルリクをなんとなく見ていて発見して面白そうだったので書いてみました。 (まだ未リリースっぽいです)
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;
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした