Ich denke Simas's answer ist die beste, aber hier ist eine Hacky Version, falls Sie das bevorzugen.
ViewTools.findActionBarTitle(getWindow().getDecorView()).setOnClickListener(...);
Diese sollte universal sein, dass es funktioniert mit:
- Lager Android
ActionBar
Theme.AppCompat
Unterstützung ActionBar
- v21-Stil
setActionBar
Verwendung <Toolbar android:id="@+id/action_bar"
oder in dem aufgeblasenen Toolbar
als root
- v21-Stil
setSupportActionBar
Verwendung <android.support.v7.widget.Toolbar android:id="@id/action_bar"
oder Pass in den aufgeblasenen Toolbar
als root
- benutzerdefinierten
Toolbar
Implementierungen passieren, eine wenig Anpassung benötigt
aber dann könnte man kapseln das in dieser benutzerdefinierten Klasse.
Obwohl ich nur mit Unterstützung getestet: v22.
/** @param root usually Activity.getWindow().getDecorView() or your custom Toolbar */
public static @Nullable View findActionBarTitle(@NonNull View root) {
return findActionBarItem(root, "action_bar_title", "mTitleTextView");
}
/** @param root usually Activity.getWindow().getDecorView() or your custom Toolbar */
public static @Nullable View findActionBarSubTitle(@NonNull View root) {
return findActionBarItem(root, "action_bar_subtitle", "mSubtitleTextView");
}
private static @Nullable View findActionBarItem(@NonNull View root,
@NonNull String resourceName, @NonNull String toolbarFieldName) {
View result = findViewSupportOrAndroid(root, resourceName);
if (result == null) {
View actionBar = findViewSupportOrAndroid(root, "action_bar");
if (actionBar != null) {
result = reflectiveRead(actionBar, toolbarFieldName);
}
}
if (result == null && root.getClass().getName().endsWith("widget.Toolbar")) {
result = reflectiveRead(root, toolbarFieldName);
}
return result;
}
@SuppressWarnings("ConstantConditions")
private static @Nullable View findViewSupportOrAndroid(@NonNull View root, @NonNull String resourceName) {
Context context = root.getContext();
View result = null;
if (result == null) {
int supportID = context.getResources().getIdentifier(resourceName, "id", context.getPackageName());
result = root.findViewById(supportID);
}
if (result == null) {
int androidID = context.getResources().getIdentifier(resourceName, "id", "android");
result = root.findViewById(androidID);
}
return result;
}
@SuppressWarnings("unchecked")
public static <T> @Nullable T reflectiveRead(@NonNull Object object, @NonNull String fieldName) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (T)field.get(object);
} catch (Exception ex) {
Log.w("HACK", "Cannot read " + fieldName + " in " + object, ex);
}
return null;
}
Ist es das gleiche, das Sie suchen? [Wie kann ich einen Klick auf den ActionBar-Titel erkennen?] (Http://stackoverflow.com/questions/7981394/how-can-i-detect-a-click-on-the-actionbar-title) –
@PareshMayani so das ist nicht möglich ? –