繁体   English   中英

Android 按钮抛出 IllegalStateException

[英]Android Button throws IllegalStateException

所以我正在尝试构建一个简单应用程序的基础,我可以通过单击按钮来切换活动。 我的主要活动到第二个活动都可以正常工作; 但是,我无法让它回到主要活动。

当前,当我单击按钮时出现此错误: java.lang.IllegalStateException :无法在 android 的父级或祖先上下文中找到方法 NewBack(View):onClick 在视图上定义的属性 class com.google184824 .MaterialButton with id 'back'

这是第二个活动中的代码:

package com.example.homework4;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CreateQuestion extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_question);
    }

    public void NewBack(View v){
        setContentView(R.layout.activity_main);
    }

}

这是我的 xml 文件中按钮的代码:

<Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="153dp"
        android:onClick="NewBack"
        android:text="GO BACK"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/submit" />

我也尝试过设置一个具有相同结果的onClickListener 我敢肯定这是一个简单的修复,我似乎无法弄清楚!

如果您想在需要更换的活动之间导航

public void NewBack(View v){
    setContentView(R.layout.activity_main);
}

public void newBack(View v){
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);

}

PS 不要在 function 名称中使用大写。 所以如果 function 被称为 newBack

也在 XML 文件中更改它,例如:

<Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="153dp"
        android:onClick="newBack"
        android:text="GO BACK"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/submit" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM