Android查找工具栏



我在应用中有两个模块。在第二个中,我有活动作为上下文。该任务需要通过第二个模块的工具栏动画。问题是我不想将工具栏对象从1到2个模块发送,也许有某种方法可以通过活动obj?

这一点都不困难。如果您会阅读此答案,可以看到工具栏具有私人ID,可以使用getResources().getIdentifier("action_bar", "id", "android")找到。但是在某些情况下,当您尝试通过此ID查找视图时,无效。然后,您应该尝试使用第二种方法递归找到它。希望这对您有帮助。

    @Nullable public Toolbar getToolbarView(@NonNull Context context) {
        Activity activity = ((Activity) context);
        int resId = context.getResources().getIdentifier("action_bar", "id", "android");
        Toolbar toolbar = (Toolbar) activity.findViewById(resId);
        if (toolbar == null) {
            toolbar = findToolbar((ViewGroup) activity.findViewById(android.R.id.content));
        }
        return toolbar;
    }
    private Toolbar findToolbar(@NonNull ViewGroup viewGroup) {
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            View view = viewGroup.getChildAt(i);
            if (view.getClass().getName().equals("android.support.v7.widget.Toolbar")
                    || view.getClass().getName().equals("android.widget.Toolbar")) {
                return (Toolbar) view;
            } else if (view instanceof ViewGroup) {
                return findToolbar((ViewGroup) view);
            }
        }
        return null;
    }

最新更新