I have two modules in the app. In the second I have activity as context. The task requires toolbar animation through the second module. The problem in that I don't want to send toolbar object from 1 to 2 module, maybe there is some way to get it through the Activity obj?
Asked
Active
Viewed 1,571 times
1
-
you have to make `Toolbar` object to public. – Asif Patel Feb 18 '17 at 21:18
-
Can you list some code or be more verbose? – A P Feb 18 '17 at 21:18
-
I cannot, it's just in the paper. I have two modules in the app. In the second I have activity as context. The task requires toolbar animation through the second module. The problem in that I don't want to send toolbar object from 1 to 2 module, maybe there is some way to get it through the Activity obj? – Near1999 Feb 18 '17 at 21:21
-
activity.getToolbar() – Divers Feb 18 '17 at 21:29
-
@Divers, there is no such method. I can get ActionBar, but then I cannot cast it to the Toolbar and animate it as I needed. – Near1999 Feb 18 '17 at 21:33
-
Of course you need to create that method which returns instance of your toolbar. – Divers Feb 19 '17 at 08:18
1 Answers
2
This is not difficult at all. If you will read this answer, you can see that toolbar has private id whitch can get be found with getResources().getIdentifier("action_bar", "id", "android")
. But in some cases, when you will try to find view by this id, comes null. Then you should try to find it recursively with the second method. Hope this might help you.
@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;
}

Community
- 1
- 1

Alexander Goncharenko
- 954
- 6
- 16