java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button

huangapple go评论146阅读模式
英文:

java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button

问题

问题:
我在 Android Studio 中有一个 Java/XML 文件。我需要添加两个按钮:一个用于“地图页面”,第二个用于“创建新帐户”(注册活动)。第一个按钮正常工作,但第二个按钮会关闭我的应用程序。问题是什么?

我知道的:
如果 XML 文件为空,则可以正常使用转到 XML 文件的按钮。

错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sampleapp, PID: 8062
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sampleapp/com.example.sampleapp.SignUpActivity}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button
        ...
     Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button
        at com.example.sampleapp.SignUpActivity.onCreate(SignUpActivity.java:33)
        ...

脚本:

LoginActivity.java:

...

activity_login.xml:

...

SignUpActivity.java:

...

activity_sign_up.xml:

...
英文:

Problem:
I have a java/xml file in android studio. I need to play two buttons; One for "Map page" and second for "Create new account" (Signup activity). The first button work, but the second close my app. What is the problem?

What I know:
if it is empty xml file the button for to go to the xml file work.

The errors:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sampleapp, PID: 8062
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sampleapp/com.example.sampleapp.SignUpActivity}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button
        at com.example.sampleapp.SignUpActivity.onCreate(SignUpActivity.java:33)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 

Scripts:

LoginActivity.java:

package com.example.sampleapp;

import androidx.appcompat.app.AppCompatActivity;

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

public class LoginActivity extends AppCompatActivity {
    public EditText username;
    public EditText password;
    public TextView errorView;
    public Button login;
    public Button createNewAccount;

    public void initMapPage(){
        Intent mapPage = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(mapPage);
        finish();
    }

    public void initSignUpPage(){
        Intent signUpPage = new Intent(LoginActivity.this, SignUpActivity.class);
        startActivity(signUpPage);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = (EditText) findViewById(R.id.UsernameBox);
        password = (EditText) findViewById(R.id.PasswordBox);
        errorView = (TextView) findViewById(R.id.errorView);
        login = (Button) findViewById(R.id.LoginButton);
        createNewAccount = (Button) findViewById(R.id.SignupButton);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String errorMsg = "";
                if (username.getText().toString().equals("") || password.getText().toString().equals("")) {
                    if (username.getText().toString().equals("")) {
                        errorMsg += "Username block is empty\n";
                    }
                    if (password.getText().toString().equals("")) {
                        errorMsg += "Password block is empty\n";
                    }

                    errorView.setText(errorMsg);
                }
                else {
                    initMapPage();
                }
            }
        });

        createNewAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initSignUpPage();
            }
        });
    }
}

activity_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<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=".LoginActivity">

    <TextView
        android:id="@+id/WelcomeBox"
        android:layout_width="210dp"
        android:layout_height="101dp"
        android:layout_marginTop="64dp"
        android:text="Welcome \nTo Our App!"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/UsernameBox"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:hint="Username"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/WelcomeBox" />

    <EditText
        android:id="@+id/PasswordBox"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:layout_marginTop="24dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/UsernameBox" />

    <Button
        android:id="@+id/SignupButton"
        android:layout_width="237dp"
        android:layout_height="55dp"
        android:layout_marginTop="24dp"
        android:text="Create New Acount"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView4" />

    <Button
        android:id="@+id/LoginButton"
        android:layout_width="115dp"
        android:layout_height="63dp"
        android:layout_marginTop="12dp"
        android:text="LOGIN"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/errorView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="60dp"
        android:layout_height="29dp"
        android:layout_marginTop="24dp"
        android:text="OR"
        android:textAlignment="center"
        android:textColor="#D3000000"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/LoginButton" />

    <TextView
        android:id="@+id/errorView"
        android:layout_width="209dp"
        android:layout_height="62dp"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:textAlignment="center"
        android:textColor="#FF0000"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/PasswordBox" />

</androidx.constraintlayout.widget.ConstraintLayout>

SignUpActivity.java:

package com.example.sampleapp;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SignUpActivity extends AppCompatActivity {

    public Button backToLogin;
    public Button SignUp;
    public EditText username;
    public EditText password;
    public EditText email;


    public void initLoginPage(){
        Intent loginPage = new Intent(SignUpActivity.this, LoginActivity.class);
        startActivity(loginPage);
        finish();
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        SignUp = (Button) findViewById(R.id.suButton);
        backToLogin = (Button) findViewById(R.id.back_to_login);
        username = (EditText) findViewById(R.id.UsernameBoxSignUp);
        password = (EditText) findViewById(R.id.PasswordBoxSignUp);
        email = (EditText) findViewById(R.id.EmailBox);

        backToLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initLoginPage();
            }
        });
    }
}

activity_sign_up.xml:

<?xml version="1.0" encoding="utf-8"?>
<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=".SignUpActivity">

    <EditText
        android:id="@+id/UsernameBoxSignUp"
        android:layout_width="300dp"
        android:layout_height="40dp"
        android:layout_marginStart="54dp"
        android:layout_marginTop="160dp"
        android:ems="10"
        android:hint="Username"
        android:inputType="textPersonName"
        android:textSize="18sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/back_to_login" />

    <EditText
        android:id="@+id/PasswordBoxSignUp"
        android:layout_width="300dp"
        android:layout_height="40dp"
        android:layout_marginStart="55dp"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/EmailBox" />

    <Button
        android:id="@+id/suButton"
        android:layout_width="170dp"
        android:layout_height="53dp"
        android:layout_marginStart="120dp"
        android:layout_marginTop="36dp"
        android:text="SignUp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/PasswordBoxSignUp" />

    <EditText
        android:id="@+id/EmailBox"
        android:layout_width="300dp"
        android:layout_height="40dp"
        android:layout_marginStart="44dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/UsernameBoxSignUp" />

    <ImageButton
        android:id="@+id/back_to_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="54dp"
        android:layout_marginTop="28dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="?attr/actionModeCloseDrawable" />

</androidx.constraintlayout.widget.ConstraintLayout>

答案1

得分: 2

问题在于 ImageButton(因此也包括 appcompat 版本)是 ImageView 的子类,而不是 Button 的子类。您应该将转换更改为那样,或者如果您仅使用 View 的方法如 setOnClickListener,则将其完全移除。

英文:

The problem is that ImageButton (and thus also the appcompat version) is a subclass of ImageView, not of Button. You should either change the cast to that, or just remove it entirely if you're only using View methods like setOnClickListener.

答案2

得分: 0

用户名或密码文本已设置?

Android:text = ""
提示只是一个提示,不是实际的响应。因此,在寻找尚未设置的内容时会出错。

英文:

Is the username or password text set up?

Android:text="" <!-- If you don't do this, it will be null instead -->
A hint is just a hint, not the actual response. So it gets an error when it looking for something that's not even set up yet.

答案3

得分: 0

Your calling SignUpActivity twice

Place the intent

Intent signUpPage = new Intent(LoginActivity.this, SignUpActivity.class);
        startActivity(signUpPage);

on onClick method

and don't forget to add android:onClick="OnCreateAccount" on your button

英文:

Your calling SignUpActivity twice

Place the intent

Intent signUpPage = new Intent(LoginActivity.this, SignUpActivity.class);
        startActivity(signUpPage);

on onClick method

and don't forget to add android:onClick=&quot;OnCreateAccount&quot; on your button

答案4

得分: 0

你正在将按钮转换为图像按钮

只需按照这个简单的步骤操作

进入 'SignUpActivity.java',然后

public ImageButton backToLogin;
backToLogin = (ImageButton) findViewById(R.id.back_to_login);
英文:

You are casting button on imagebutton

Just follow this simple step

go to 'SignUpActivity.java' then

public ImageButton backToLogin;
backToLogin = (ImageButton) findViewById(R.id.back_to_login);

huangapple
  • 本文由 发表于 2020年4月7日 05:58:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/61069619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定