android - 在分隔的工具栏中具有onClick的ImageButton

标签 android onclick crash android-toolbar android-imagebutton

您好:)我想在工具栏中的ImageButton中添加onClick方法。

它使用onBackPressed()起作用,但不能通过ImageButton-Click起作用。该应用程序崩溃了,但是我无法从控制台读取错误消息,而且我还没有弄清楚如何正确调试它。

您能帮我解决可能缺少的内容吗?
非常感谢 :)

toolbar_room.xml

<android.support.v7.widget.Toolbar 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:id="@+id/toolbar_room"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton
        android:layout_width="?attr/actionBarSize"
        android:layout_height="match_parent"
        android:background="@drawable/ic_back"
        android:id="@+id/btn_roomBack"
        android:onClick="backToMain"/>
</LinearLayout>

activity_room.xml
<android.support.v7.widget.LinearLayoutCompat 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="de.hftl.smartcast.RoomActivity"
android:orientation="vertical">

<include layout="@layout/toolbar_room"></include>
//Code

RoomActivity.java
public class RoomActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_room);
}
public void backToMain(){
    AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
    alertDlg.setMessage("Text");
    alertDlg.setCancelable(false);

    alertDlg.setPositiveButton("yeah", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            RoomActivity.super.onBackPressed();
        }
    });
    alertDlg.setNegativeButton("nope", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    alertDlg.create().show();
}

注意:我添加了android:parentActivityName=".RoomActivity"到我的AndroidManifest.xml。

最佳答案

您应该像这样通过XML传递View参数以供onClick使用。

public void backToMain(View v){

关于android - 在分隔的工具栏中具有onClick的ImageButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47971066/

相关文章:

android - 由于 java.lang.IllegalArgumentException : column '_id' does not exist,应用程序在启动时崩溃

使用 Xamarin 注册 Google Cloud Messaging 时出现 Java.Lang.LinkageError

android - 使用适用于 Android 和 ADT 的 Google Cloud Endpoints

android - 如何在Android中单击Alert Box中的按钮时关闭应用程序?

asp.net - Javascript 在 IE 和 FF 中被调用,但在 Chrome 中却没有被调用,为什么?

Jquery 点击选择器/数据

android - 如何修复损坏的应用程序?

Android - API 10 没有 ActionBar

Android 添加新日历

python - 在脚本崩溃之前调用函数?