我在应用程序中有一个客户工具栏,如下所示有一个按钮调用注销
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="80dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="@android:color/transparent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="24dp">
<Button
android:id="@+id/toolbar_logo_image"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="4dp"
android:layout_centerVertical="true"
android:background="@drawable/logo" />
<EditText
android:id="@+id/toolbar_search_field"
android:layout_width="280dp"
android:layout_height="36dp"
android:textSize="20dp"
android:hint="Search"
android:textColorHint="@color/white"
android:layout_toEndOf="@+id/toolbar_logo_image"
android:layout_centerVertical="true"
android:textColor="@android:color/white"
android:background="@android:color/transparent"
android:drawablePadding="2dp"
android:drawableStart="@drawable/ic_search_24dp"
tools:textColor="@android:color/black"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
我在我的主要活动中包含了这个工具栏,如下所示
<include
android:id="@+id/main_page_toolbar"
layout="@layout/app_bar_toolbar">
</include>
在我的主要活动中,我得到了如下所示的工具栏
mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
如何访问该工具栏中的按钮我想创建一个 onclickevent 我该怎么做?
您可以findViewById
在每个视图上使用。所以你可以使用
Button button = (Button) mToolbar.findViewById(R.id.toolbar_logo_image);
但是当您在根布局中包含工具栏布局时,它应该足以使用
Button button = (Button) findViewById(R.id.toolbar_logo_image);
两者都应该工作。
编辑:你的 app_bar_toolbar.xml 有一个FrameLayout
as 根元素,但在代码中你试图将它转换为Toolbar
. 这是行不通的,并且会因 ClassCastException 而崩溃。因此,将您的 FrameLayout 更改为 Toolbar 或正确投射 FrameLayout。取决于您的需求。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句