Я получаю непонятную ошибку:
07-19 22:14:50.750 23192-23192/com.example.shun.zeatbeta E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shun.zeatbeta, PID: 23192
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shun.zeatbeta/com.example.shun.zeatbeta.ReauthenticateActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.Button
at com.example.shun.zeatbeta.ReauthenticateActivity.onCreate(ReauthenticateActivity.java:59)
at android.app.Activity.performCreate(Activity.java:6942)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Строка, приводящая к сбою программы при работе:
private Button loginButton;
loginButton = (Button) findViewById(R.id.loginButton);
activity_reauthenticate2.xml:
<com.example.shun.zeatbeta.ComfortaaButton
android:id = "@+id/loginButton"
android:layout_width = "match_parent"
android:layout_height = "@dimen/button_height"
android:layout_marginTop = "20dp"
android:background = "@drawable/round_button_blue"
android:text = "@string/login"
android:textColor = "@color/white"
android:textSize = "15dp"
app:layout_constraintBottom_toTopOf = "@id/facebookWrapper"
app:layout_constraintTop_toBottomOf = "@id/textFields" />
ComfortaaButton.java
package com.example.shun.zeatbeta;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
public class ComfortaaButton extends AppCompatButton {
public ComfortaaButton(Context context) {
super(context);
init();
}
public ComfortaaButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ComfortaaButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/Comfortaa-Regular.ttf");
setTypeface(tf, 1);
}
}
Почему я получаю эту ошибку? Кнопка явно Button, а не ImageButton. Я пробовал очистить проект, перезапустить, очистить кеш и т. д. Я даже попытался создать новый файл действия и макета, и ошибка вернулась!
ОБНОВЛЕНИЕ: я получил эту информацию о строке активности, приводящей к сбою кода:
Unexpected cast to AppCompatButton: layout tag was ImageButton (Id bound to an ImageButton in activity_landing_page.xml) less... (⌘F1)
Keeps track of the view types associated with ids and if it finds a usage of the id in the Java code it ensures that it is treated as the same type.
Таким образом, похоже, что он ищет действия по идентификатору в activity_landing_page.xml, а не в activity_reauthenticate2.xml. Почему? Как я могу это изменить?
приложение Gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion '27.0.3'
defaultConfig {
applicationId "com.example.s.company"
minSdkVersion 17
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'com.android.support:support-v4:27.1.1'
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
implementation 'com.facebook.android:facebook-android-sdk:4.33.0'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
implementation 'com.stripe:stripe-android:6.1.2'
compile 'com.google.firebase:firebase-auth:15.0.0'
compile 'com.google.firebase:firebase-core:15.0.0'
compile 'com.google.firebase:firebase-database:15.0.0'
compile 'com.google.firebase:firebase-storage:15.0.0'
compile 'com.firebaseui:firebase-ui-storage:3.3.1'
compile 'com.android.volley:volley:1.1.0'
compile 'com.felipecsl.asymmetricgridview:library:2.0.1'
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.github.ittianyu:BottomNavigationViewEx:1.2.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.android.support.constraint:constraint-layout:1.1.0'
compile 'com.github.arimorty:floatingsearchview:2.1.1'
implementation 'info.hoang8f:android-segmented:1.0.6'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
@mTak Я воссоздал класс со шрифтом, и он работает для меня
Обновлять: Кнопка тоже должна нормально работать.
Запуск представления как AppCompatButton,
private AppCompatButton mLoginButton;
mLoginButton=findViewById(R.id.loginButton);
Пробовал private AppCompatButton loginButton; loginButton = (AppCompatButton) findViewById(R.id.loginButton);, и я получил java.lang.ClassCastException: android.support.v7.widget.AppCompatImageButton cannot be cast to android.support.v7.widget.AppCompatButton. AppCompatButton - это подкласс Button, поэтому я думаю, что мой код должен работать ...
Вы можете опубликовать свой build.gradle?
@Sahand Я не могу воспроизвести проблему, я создал настраиваемую кнопку, как и вы. И Button, и AppCompatButton у меня отлично работают. Да, вы правы, кнопка тоже должна работать. Можете ли вы опубликовать полный xml (также вы можете удалить файл градиента уровня проекта)
@Sahand вы пытаетесь сделать какую-либо анимацию макета ограничений или изменить макет с помощью наборов ограничений?
Для вашего loginButton должен быть другой повторяющийся идентификатор. Просто убедитесь, что вы получите правильный импорт, когда наберете R.id.loginButton из loginButton = (Button) findViewById(R.id.loginButton); для своей целевой Activity или xml.
Как мне убедиться?
Введите еще раз код findViewById(R.id.loginButton), но перед тем, как ввести loginButton, проверьте или дождитесь предложения, есть ли другие варианты для идентификатора loginButton.
// Эта ошибка возникла, когда я ошибочно закодировал val deleteButton = itemView.findViewById <(Кнопка)> (R.id.item_delete_button) // На самом деле в XML-файле я использовал представление изображения вместо кнопки, чтобы // сделать это изображение кликабельным. // Итак, я изменил <(Button)> на <(ImageView)>. Потом эта проблема была решена.
Это не похоже на заданный вопрос, вопрос ОП не обязательно был ошибкой. Кроме того, этот вопрос был опубликован более 2 лет назад, поэтому я бы не сказал, что он нуждается в дополнительных ответах.
Ваш код отлично работает для меня, за исключением, конечно, части инициализации ComfortaaButton, где вы устанавливаете шрифт, который я закомментировал