Android 如何使 Toolbar 标题可以像在 ActionBar 上一样点击,而不将其设置为 ActionBar?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26495530/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:36:58  来源:igfitidea点击:

How to make the Toolbar title clickable exactly like on ActionBar, without setting it as ActionBar?

androidandroid-actionbar-compatandroid-toolbar

提问by android developer

Background

背景

I wish to show an ActionBar on PreferenceActivity, as it's not available for pre-Honeycomb devices (even in the support library).

我希望在 PreferenceActivity 上显示一个 ActionBar,因为它不适用于蜂窝式设备(即使在支持库中)。

Because such a class isn't available on the support library, I can't just call "setSupportActionBar" . I also don't wish to use a library (like this one) since all of the libraries I've found still use Holo style, so they didn't get updated so far, with this in mind.

因为支持库上没有这样的类,所以我不能只调用 "setSupportActionBar" 。我也不希望使用一个库(比如这个),因为我发现的所有库仍然使用 Holo 风格,所以到目前为止它们没有得到更新,考虑到这一点。

To do this, I'm trying to mimic the look&feel of the title of the ActionBar into the new Toolbarclass, that was presented on support library v7 .

为此,我试图将 ActionBar 标题的外观和感觉模仿到新的Toolbar类中,该类出现在支持库 v7 中。

The problem

问题

I've succeeded putting a title and a an "up" button, but I can't find out how to make them clickable like a normal action bar, including the effect of touching.

我已经成功地放置了一个标题和一个“向上”按钮,但我不知道如何使它们像普通操作栏一样可点击,包括触摸的效果。

The code

编码

Here's the code:

这是代码:

SettingsActivity.java

设置Activity.java

public class SettingsActivity extends PreferenceActivity
  {
  @Override
  protected void onCreate(final Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    addPreferencesFromResource(R.xml.pref_general);
    final Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(getResources().getColor(R.color.windowBackgroundColor));
    toolbar.setTitle("Settings");
    toolbar.setClickable(true);
    toolbar.setLogo(getResIdFromAttribute(this,R.attr.homeAsUpIndicator));
    }

  public static int getResIdFromAttribute(final Activity activity,final int attr)
    {
    if(attr==0)
      return 0;
    final TypedValue typedvalueattr=new TypedValue();
    activity.getTheme().resolveAttribute(attr,typedvalueattr,true);
    return typedvalueattr.resourceId;
    }
  }

activity_settings.xml

活动设置.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.antonioleiva.materialeverywhere.SettingsActivity" >

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <View
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/abs__ab_solid_shadow_holo" />

        <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

</LinearLayout>

What I've tried

我试过的

I've tried all of the click listeners types of the Toolbar class, but none helped.

我已经尝试了 Toolbar 类的所有点击侦听器类型,但都没有帮助。

The only thing that almost worked is to use "setNavigationIcon" instead of "setLogo", but that actually makes the title&icon being clicakable, yet only the icon shows its effect of being clicked (even if I click on the title).

唯一几乎有效的方法是使用“setNavigationIcon”而不是“setLogo”,但这实际上使标题和图标可点击,但只有图标显示其被点击的效果(即使我点击标题)。

The question

问题

How can I add the look & feel of the Toolbar, to have the title & logo of it to look like the ActionBar?

如何添加工具栏的外观和感觉,使其标题和徽标看起来像 ActionBar?

回答by prom85

I had the same problem and found a quite convenient way for it (for the clickable title), doing this with the Toolbar. It does not matter, if the Toolbaris used as ActionBaror not, it works for both cases.

我遇到了同样的问题,并找到了一种非常方便的方法(对于可点击的标题),使用Toolbar. 不管是否Toolbar使用ActionBar,它都适用于两种情况。

Just set the click listener on the Toolbaritself, this will result in the complete Toolbarfiring the click listener, if not a menu item or the home icon is clicked. For me, that's exactly what I expect...

只需在其Toolbar自身上设置点击侦听器,这将导致完全Toolbar触发点击侦听器,如果没有点击菜单项或主页图标。对我来说,这正是我所期望的......

For example:

例如:

 setSupportActionBar(toolbar);
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
 toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getThis(), "Toolbar title clicked", Toast.LENGTH_SHORT).show();
        }
    });

onOptionsItemSelected, home click and similar WON'Tfire the onClickevent. Seems like a good solution

onOptionsItemSelected, home click 和类似的不会触发onClick事件。似乎是一个很好的解决方案

回答by MrEngineer13

Just remember that the Toolbar is basically just a ViewGroup so you can add a TextView to it and listen to onClick events like that.

请记住,工具栏基本上只是一个 ViewGroup,因此您可以向其中添加一个 TextView 并侦听这样的 onClick 事件。

Add TextView to Toolbar in XML:

将 TextView 添加到 XML 中的工具栏:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/action_bar_bkgnd"
    app:theme="@style/ToolBarTheme" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Settings"
        android:id="@+id/toolbar_title" />

    </android.support.v7.widget.Toolbar>

Listen for clicks in your Activity:

侦听您的活动中的点击次数:

toolbarTop.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG,"Clicked");
        }
    });

回答by user496854

You can actually do it pretty easily without having to do any workarounds. You just need to cycle through all the child views of the Toolbar, and find a TextViewthat's got the correct title text.

实际上,您可以非常轻松地做到这一点,而无需采取任何变通办法。您只需要遍历 的所有子视图Toolbar,并找到具有TextView正确标题文本的 。

String title = toolbar.getTitle();
for(int i = 0; i < toolbar.getChildCount(); i++){
    View tmpView = toolbar.getChildAt(i);
    if("android.support.v7.widget.AppCompatTextView".equals(tmpView.getClass().getName())){
        if(((AppCompatTextView) tmpView).getText().equals(title)){
            tmpView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //do whatever you want here
                }
            });
        }
    }
}