我正在应用程序中从ActionBar迁移到工具栏。 但我不知道如何显示和设置单击事件在工具栏上的后退箭头,就像我在动作栏上做的那样。

使用ActionBar,我调用mActionbar.setDisplayHomeAsUpEnabled(true)。 但是没有类似的方法。

有没有人遇到过这种情况,并以某种方式找到了解决它的方法?


当前回答

你很容易就能做到。

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

学分: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e

其他回答

如果不想创建自定义工具栏,可以这样做

public class GalleryActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...  
        getSupportActionBar().setTitle("Select Image");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
}                     

在你的AndroidManifest.xml中

<activity
    android:name=".GalleryActivity"
    android:theme="@style/Theme.AppCompat.Light">        
</activity>

你也可以把这个android:theme="@style/ theme . appcompat . "轻"到< application >标签,用于应用于所有活动

我从谷歌开发者文档中使用了这个方法:

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  getActionBar().setDisplayHomeAsUpEnabled(true);
}

如果你得到一个空指针异常,这可能取决于主题。尝试在清单中使用不同的主题,或者使用以下方法:

@Override
public void onCreate(Bundle savedInstanceState) {
  ...
  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

然后在清单中,我为当前活动设置父活动:

<activity
        android:name="com.example.myapp.MyCurrentActivity"
        android:label="@string/title_activity_display_message"
     android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myapp.MyMainActivity" />
</activity>

我希望这对你有帮助!

如果您正在使用JetPack导航。

这是MainActivity的布局

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                               xmlns:app="http://schemas.android.com/apk/res-auto"
                                               xmlns:tools="http://schemas.android.com/tools"
                                               android:layout_width="match_parent"
                                               android:layout_height="match_parent"
                                               tools:context=".MainActivity">

<androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</androidx.appcompat.widget.Toolbar>

<fragment
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        app:layout_constraintBottom_toTopOf="parent"
        app:navGraph="@navigation/nav_graph"/>

在activity类的onCreate()中设置你的工具栏,如下所示。

val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return

val navController = navHostFragment.findNavController()
val toolBar = findViewById<Toolbar>(R.id.toolBar)
setSupportActionBar(toolBar) // To set toolBar as ActionBar
setupActionBarWithNavController(navController)

如果需要,将在工具栏上创建一个后退按钮,并处理后退按钮功能。 如果你需要写一个CustomBack功能,在你的onCreate()方法上创建一个callBack,如下所示

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
    }

从文档:https://developer.android.com/guide/navigation/navigation-custom-back

如果你想要得到工具栏上的后退箭头,而不是设置为你的SupportActionBar:

(kotlin)

val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbarFilter.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
toolbarFilter.setNavigationOnClickListener { fragmentManager?.popBackStack() }

从属性中获取res:

@AnyRes
fun getResIdFromAttribute(context: Context, @AttrRes attr: Int): Int {
    if (attr == 0) return 0
    val typedValueAttr = TypedValue()
    context.theme.resolveAttribute(attr, typedValueAttr, true)
    return typedValueAttr.resourceId
}

您可以随时在工具栏中添加相对布局或线性布局,并在工具栏中任意位置放置后退图标或关闭图标的图像视图

例如,我在工具栏中使用了相对布局

 <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_top"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:minHeight="?attr/actionBarSize"
                android:nextFocusDown="@id/netflixVideoGridView"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">


                    <TextView

                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Myflix"
                        android:textAllCaps="true"
                        android:textSize="19sp"
                        android:textColor="@color/red"
                        android:textStyle="bold" />


                    <ImageView
                        android:id="@+id/closeMyFlix"
                        android:layout_alignParentRight="true"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        app:srcCompat="@drawable/vector_close" />


                </RelativeLayout>

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

它是这样的:

你可以在图像视图中从活动或片段中添加点击监听器。

  closeMyFlix.setOnClickListener({
            Navigator.instance.showFireTV(  activity!!.supportFragmentManager)
        })