【问题标题】:How to add TextView in same location of title in Toolbar?如何在工具栏中标题的相同位置添加 TextView?
【发布时间】:2017-02-18 13:45:30
【问题描述】:

我的 xml 文件中有一个工具栏,其中没有定义子视图。当我们调用setSupportActionBar(toolbar) 时,我想在工具栏中默认标题的确切位置添加一个 TextView。在特定事件上,我喜欢在特定事件的情况下淡入或淡出这两个视图。

我尝试在活动的onCreate() 中执行以下操作,但除了工具栏中的默认标题外,没有任何内容可见。

    TextView tv = new TextView(this);
    tv.setLayoutParams(toolbarTitle.getLayoutParams());
    tv.setHeight(toolbarTitle.getHeight());
    tv.setWidth(toolbarTitle.getWidth());
    tv.setText("Other Title");
    tv.setLeft(toolbarTitle.getLeft());
    toolbar.addView(tv);

我也尝试在工具栏内添加一个RelativeLayout,宽度和高度设置为匹配父级,但这一次,工具栏的默认标题TextView消失了。

如何在工具栏中默认标题TextView的确切位置添加另一个TextView?

【问题讨论】:

    标签: android textview android-toolbar


    【解决方案1】:

    您可以使用AppBarLayout,如下所示

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.AppBarLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/toolbar_layout"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     >
    
    <android.support.v7.widget.Toolbar
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      android:background="?attr/colorPrimary"
      >
    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/aadhaar_sign_up"
        android:textColor="@color/white"
        android:textSize="18.0sp"
        app:fontName="Font-Medium.ttf"
        />
     </android.support.v7.widget.Toolbar>
    
    </android.support.design.widget.AppBarLayout>
    

    然后你使用下面的文本视图

    Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    ((TextView) toolbar.findViewById(R.id.toolbar_title)).setText(title);
    

    【讨论】:

    • 这将提供一个文本视图,对吗?我希望原始文本视图保持在添加一个的位置
    • 我希望保留原始标题 TextView 但是当我添加另一个 TextView 时它会消失。我的问题是如何保留原始 TextView 并在其上放置另一个 TextView :/
    【解决方案2】:

    我在我的活动的onCreate() 方法中使用getSupportActionBar().setDisplayShowTitleEnabled(false) 禁用工具栏中的标题,并将两个重叠的textViews 用relativeLayout 封装在布局中的工具栏中。然后我根据需要为它们设置动画。在更改文本时,我使用了titleTextView.setText() 而不是toolbar.setTitle() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多