如何在工具栏上的后退箭头上显示和设置单击事件 [英] How to display and set click event on Back Arrow on Toolbar
本文介绍了如何在工具栏上的后退箭头上显示和设置单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
怎么能我在android工具栏中设置了箭头,还应用了点击监听器?
How can I set back arrow in android toolbar and also apply click listener?
推荐答案
首先制作一个 toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="@color/colorPrimary"
local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
然后将其包含在 activity_main.xml
中这样:
then include it in activity_main.xml
like this way:
<LinearLayout
android:id="@+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
</LinearLayout>
然后在你的 MainActivity.java
文件中,把这段代码:
then in your MainActivity.java
file, put this code:
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("MyTitle");
要在背面添加监听器,请使用以下方法:
To add listener on back press, use following method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
这篇关于如何在工具栏上的后退箭头上显示和设置单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文