在 Android 中的操作栏标题上设置 OnClick 侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24838155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set OnClick Listener on Action Bar Title in Android
提问by N Sharma
I am working on android application where I am using ActionBar
so there one is navigation drawer icon to open it and title of ActionBar
in ActionBar
. I want to set a click listener on title of ActionBar
such that it start a new Activity
and set click listener different on navigation drawer icon to open navigation drawer menu.
我正在使用我正在使用的 android 应用程序,ActionBar
所以有一个导航抽屉图标可以打开它和ActionBar
in 的标题ActionBar
。我想在标题上设置一个点击侦听器,ActionBar
以便它启动一个新的Activity
并在导航抽屉图标上设置不同的点击侦听器以打开导航抽屉菜单。
I achieved a click on navigation drawer icon but when I click on title of ActionBar
title also then it open the navigation drawer menu. Is there any way to set different click listener on title of ActionBar
.
我点击了导航抽屉图标,但是当我点击标题标题时,ActionBar
它也会打开导航抽屉菜单。有什么办法可以在ActionBar
.
Thanks in advance.
提前致谢。
采纳答案by Jake Weso
Try adding this code under the onCreate() function. This will grab the resource the action bar title is under, and assign it an id you can use to add an OnClickListener to. Let me know how it goes!
尝试在 onCreate() 函数下添加此代码。这将获取操作栏标题所在的资源,并为其分配一个可用于添加 OnClickListener 的 ID。让我知道事情的后续!
final int abTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
findViewById(abTitleId).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Do something
}
});
回答by Simas
You could use a custom layout for the title and assign a listener to it:
您可以为标题使用自定义布局并为其分配一个侦听器:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
// Disable the default and enable the custom
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
View customView = getLayoutInflater().inflate(R.layout.actionbar_title, null);
// Get the textview of the title
TextView customTitle = (TextView) customView.findViewById(R.id.actionbarTitle);
// Change the font family (optional)
customTitle.setTypeface(Typeface.MONOSPACE);
// Set the on click listener for the title
customTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.w("MainActivity", "ActionBar's title clicked.");
}
});
// Apply the custom view
actionBar.setCustomView(customView);
}
}
actionbar_title.xml:
actionbar_title.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/actionbarTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:text="@string/app_name"/>
</LinearLayout>
回答by TWiStErRob
I think Simas's answeris the best one, but here's a hacky version in case you prefer that.
我认为Simas 的答案是最好的答案,但如果您愿意,这里有一个 hacky 版本。
ViewTools.findActionBarTitle(getWindow().getDecorView()).setOnClickListener(...);
Thisone should be universalin that it works with:
这个应该是通用的,因为它适用于:
- stock Android
ActionBar
Theme.AppCompat
supportActionBar
- v21-style
setActionBar
use<Toolbar android:id="@+id/action_bar"
or pass in the inflatedToolbar
asroot
- v21-style
setSupportActionBar
use<android.support.v7.widget.Toolbar android:id="@id/action_bar"
or pass in the inflatedToolbar
asroot
- custom
Toolbar
implementations may need a little adjustment,
but then you could encapsulate this in that custom class.
- 股票安卓
ActionBar
Theme.AppCompat
支持ActionBar
- v21 式
setActionBar
使用<Toolbar android:id="@+id/action_bar"
或传入 inflateToolbar
asroot
- v21 式
setSupportActionBar
使用<android.support.v7.widget.Toolbar android:id="@id/action_bar"
或传入 inflateToolbar
asroot
- 自定义
Toolbar
实现可能需要一些调整,
但是您可以将其封装在该自定义类中。
Though I only tested with support:v22.
虽然我只测试了 support: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;
}
回答by Dejavu
If you are using Toolbar with support v7:21. Check out the following code:
如果您使用的是支持 v7:21 的工具栏。查看以下代码:
Field titleField = Toolbar.class.getDeclaredField("mTitleTextView");
titleField.setAccessible(true);
TextView barTitleView = (TextView) titleField.get(mToolbar);
barTitleView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
回答by jimmy0251
You can do this easily using Toolbar. Define toolbar in layout xml file as given below:
您可以使用工具栏轻松完成此操作。在布局 xml 文件中定义工具栏,如下所示:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="?colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<TextView
android:id="@+id/toolbarTitle"
style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:background="?attr/selectableItemBackground"
android:layout_width="wrap_content"
android:gravity="center_vertical"
android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>
Then you can set the listener in Activity using this code:
然后您可以使用以下代码在 Activity 中设置侦听器:
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
TextView toolbarTitle= (TextView) findViewById(R.id.toolbarTitle);
toolbarTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// DO SOMETHING HERE
}
});
回答by Chris Sprague
If you want to use the currently existing ActionBar and not the Toolbar, use the following:
如果要使用当前存在的 ActionBar 而不是 Toolbar,请使用以下命令:
ActionBar actBar = getSupportActionBar();
if(actBar != null) {
actBar.setTitle(R.string.your_ab_title);
}
//Set actions to take when the AB is clicked
Toolbar ab = findViewById(R.id.action_bar);
if(ab != null){
for (int i= 0; i < ab.getChildCount(); i++){
View child = ab.getChildAt(i);
if(child instanceof TextView || child instanceof ImageView) {
child.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "http://www.HoverDroids.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
}
}
回答by Kevin Grant
If you know the actual text that is in your Title, and you are reasonably sure that no other TextView
on the screen shares that title, you can use a recursive View tree search to find it.
如果您知道标题中的实际文本,并且您有理由确定TextView
屏幕上没有其他人共享该标题,则可以使用递归视图树搜索来查找它。
This is a great solution because it doesn't require reflection of internal knowledge of how to Toolbar is constructed, and gives you direct access to the TextView
.
这是一个很好的解决方案,因为它不需要反映如何构建工具栏的内部知识,并让您直接访问TextView
.
@Nullable
public static TextView findTextViewWithText(@Nullable View toCheck, String toFind) {
if (toCheck instanceof TextView) {
String foundText = ((TextView) toCheck).getText().toString();
if (foundText.equals(toFind)) {
return (TextView) toCheck;
}
} else if (toCheck instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) toCheck).getChildCount(); i++) {
TextView found = findTextViewWithText(((ViewGroup) toCheck).getChildAt(i), toFind);
if (found != null) {
return found;
}
}
}
return null;
}
The most reliable view to call this on is the decor view but feel free to experiment what works best for your purposes, your mileage may vary.
最可靠的观点是装饰观点,但请随意尝试最适合您的目的,您的里程可能会有所不同。
View found = findTextViewWithText(
getActivity().getWindow().getDecorView(), "My Title");
if (found != null) {
// Do something, like set a click listener
}
回答by Wajid khan
You can do this easily using Toolbar. Define toolbar in layout xml file as given below:
您可以使用工具栏轻松完成此操作。在布局 xml 文件中定义工具栏,如下所示:
<android.support.v7.widget.Toolbar
android:id="@+id/MainActivityToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/app_name"
android:textSize="30sp"
tools:ignore="RelativeOverlap"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<Button
android:id="@+id/LogOutButton"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:text="@string/logout" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
Then you can set the listener in Activity using this code:
然后您可以使用以下代码在 Activity 中设置侦听器:
setSupportActionBar((Toolbar) findViewById(R.id.MainActivityToolbar));
logOutButton = findViewById(R.id.LogOutButton);
logOutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//define your function for logout or something else
LogOut();
}
});