问题
I have a toolbar in my xml file, with no child views defined in it. I want to add a TextView on exact location of default title in toolbar when we call setSupportActionBar(toolbar)
. On particular events, I like to fade in or out these two views in case of particular events.
I tried to do the following in onCreate()
of the activity, but nothing is visible except the default title in toolbar.
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);
I also tried to add a RelativeLayout inside the toolbar with width and height set to match parent, but this time, default title TextView of toolbar disappears.
How can add another TextView on exact location of default title TextView in toolbar?
回答1:
You can use AppBarLayout
as below
<?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>
Then you use the textview as below
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
((TextView) toolbar.findViewById(R.id.toolbar_title)).setText(title);
回答2:
I disable title in toolbar using getSupportActionBar().setDisplayShowTitleEnabled(false)
in onCreate()
method of my activity and put two overlapping textViews encapsulating them with relativeLayout inside toolbar in layout. Then I animate them as I want. While changing text, I used titleTextView.setText()
rather then toolbar.setTitle()
method.
来源:https://stackoverflow.com/questions/42315935/how-to-add-textview-in-same-location-of-title-in-toolbar