Android - 使用TextView作为ToolBar标题时,ActionBar Up按钮不可见

时间:2016-10-19 13:47:23

标签: java android xml android-layout android-actionbar

我在所有活动中添加了Toolbar。但是我希望标题位于中心位置,所以根据SO的一些建议,我在TextView内创建了一个Toolbar,我可以把它放在中心。
现在,当我尝试按照本指南Adding an Up Action | Android Developers添加 Up Action 时,我没有获得任何UpButton。
这是因为在TextView内使用了Toolbar吗?因为我在SO上读到工具栏基本上是View并且可以像任何其他View一样配置,所以我不明白为什么这应该是一个问题。

  1. If that is the reason, and I'd have to use the default android:title =“我的标题”attribute in for the工具栏`,还有其他方法可以将它放在中心吗?
  2. 这个问题的解决方法是什么,以便我可以获得一个Up Action以及中心的工具栏标题?
  3. 感谢您提供任何帮助。

    XML布局

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_width="match_parent">
        <android.support.v7.widget.Toolbar
            android:id="@+id/lifeline_toolbar"
            android:elevation="4dp"
            android:background="@android:color/background_dark"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize">
            <TextView
                android:layout_gravity="center_horizontal"
                android:text="Lifeline"
                android:textStyle="bold"
                android:textSize="18sp"
                android:id="@+id/lifeline_toolbar_title"
                android:textColor="@android:color/white"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </android.support.v7.widget.Toolbar>
        <LinearLayout>
        </LinearLayout>
        <LinearLayout>
        </LinearLayout>
    </LinearLayout>
    

    Java代码

    public class ll_home extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_ll_home);
    
            Toolbar toolbar = (Toolbar) findViewById(R.id.lifeline_toolbar);
            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    

1 个答案:

答案 0 :(得分:0)

你需要设置getSupportActionBar()。setHomeButtonEnabled(true);启用“上传操作”按钮

Toolbar toolbar = (Toolbar) findViewById(R.id.lifeline_toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);