Android - how to find multiple views with common attribute

后端 未结 8 1911
野趣味
野趣味 2020-12-05 02:28

I have a layout with multiple ImageViews, some of those images need to have the same onClickListener. I would like my code to be flexible and to be able to get

8条回答
  •  一生所求
    2020-12-05 02:50

    I will share my functional-style method with a filter, can be used with StreamSupport library.

    @NonNull
    public static  Function> subViews(
        @NonNull final Function> filter
    ) {
        return view -> RefStreams.concat(
            // If current view comply target condition adds it to the result (ViewGroup too)
            filter.apply(view).map(RefStreams::of).orElse(RefStreams.empty()),
    
            // Process children if current view is a ViewGroup
            ofNullable(view).filter(__ -> __ instanceof ViewGroup).map(__ -> (ViewGroup) __)
                    .map(viewGroup -> IntStreams.range(0, viewGroup.getChildCount())
                            .mapToObj(viewGroup::getChildAt)
                            .flatMap(subViews(filter)))
                    .orElse(RefStreams.empty()));
    }
    
    @NonNull
    public static  Function> hasType(@NonNull final Class type) {
        return view -> Optional.ofNullable(view).filter(type::isInstance).map(type::cast);
    }
    
    @NonNull
    public static Function> hasTag(@NonNull final String tag) {
        return view -> Optional.ofNullable(view).filter(v -> Objects.equals(v.getTag(), tag));
    }
    

    Usage example:

    Optional.ofNullable(navigationViewWithSubViews)
                .map(subViews(hasType(NavigationView.class)))
                .orElse(RefStreams.empty())
                .forEach(__ -> __.setNavigationItemSelectedListener(this));
    

提交回复
热议问题