プルリクをなんとなく見ていて発見して面白そうだったので書いてみました。 (まだ未リリースっぽいです)
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;
}
}