developer tip

이 활동에는 Theme.AppCompat 테마 (또는 하위 항목)를 사용해야합니다.

optionbox 2020. 9. 28. 08:59
반응형

이 활동에는 Theme.AppCompat 테마 (또는 하위 항목)를 사용해야합니다.


안드로이드 스튜디오 0.4.5

사용자 정의 대화 상자를 만들기위한 Android 문서 : http://developer.android.com/guide/topics/ui/dialogs.html

사용자 지정 대화 상자가 필요한 경우 대화 API를 사용하는 대신 대화로 활동을 표시 할 수 있습니다. 활동을 만들고 <activity>매니페스트 요소 에서 테마를 Theme.Holo.Dialog로 설정하기 만하면됩니다 .

<activity android:theme="@android:style/Theme.Holo.Dialog" >

그러나 이것을 시도했을 때 다음 예외가 발생합니다.

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity

나는 다음을 지원하고 있으며 분 동안 10보다 큰 것을 사용할 수 없습니다.

minSdkVersion 10
targetSdkVersion 19

내 스타일에는 다음이 있습니다.

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

그리고 내 매니페스트에는 활동에 대해 다음이 있습니다.

 <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:theme="@android:style/Theme.Holo.Light.Dialog"
            android:name="com.ssd.register.Dialog_update"
            android:label="@string/title_activity_dialog_update" >
        </activity>

이와 같은 대화 상자를 만드는 것은 이미 레이아웃을 완료했기 때문에 제가하고 싶었던 작업이었습니다.

누구든지이 문제를 어떻게 해결할 수 있는지 말해 줄 수 있습니까?


이 문제가 발생하는 이유는 대화 테마를 적용하려는 활동이 확장 ActionBarActivity되어 AppCompat테마를 적용 해야 하기 때문입니다.

업데이트 : 확장에도이 AppCompatActivity문제가 발생합니다.

이 경우 Java 상속을에서 ActionBarActivity변경하고 Activity대화 테마를 그대로 매니페스트에 Theme.AppCompat이 아닌 그대로 둡니다.


일반적인 규칙은 코드가 이전 버전의 Android를 지원하도록하려면 AppCompat테마 가 있어야 하고 자바 코드가 AppCompatActivity. *이 지원이 필요하지 않은 활동이있는 경우 (예 : Android의 최신 버전 및 기능에만 관심이있는 경우) 테마를 적용 할 수 있지만 Java 코드는 일반 오래된 Activity.


참고 : AppCompatActivity(또는 하위 클래스, ActionBarActivity)에서로 Activity변경하면 "지원"이있는 다양한 호출도 "지원"이 없는 해당 호출로 변경해야합니다 . 그래서, 대신 getSupportFragmentManager, 전화 getFragmentManager.


파일 android:theme="@style/Theme.AppCompat.Light"의 애플리케이션 태그에 추가 하기 만하면 AndroidManifest.xml됩니다.


위의 주석에서 @MarkKeen의 답변을 복사하면 동일한 문제가 발생했습니다.

게시물 상단에 오류가 표시되었으며 경고 대화 상자를 추가 한 후에 발생했습니다. 매니페스트에 모든 관련 스타일 정보가 있습니다. 경고 작성기에서 컨텍스트 참조를 변경하여 문제가 해결되었습니다.

new android.support.v7.app.AlertDialog.Builder(getApplicationContext())

에:

new android.support.v7.app.AlertDialog.Builder(this)

그리고 더 이상 문제가 없습니다.


min sdk는 10입니다. ActionBarapi 레벨 11에서 사용할 수 있습니다. 따라서 10의 경우 사용해야 AppCompat하는 지원 라이브러리 Theme.AppCompat또는 동일한 하위 항목에서 사용합니다.

사용하다

android:theme="@style/Theme.AppCompat" >

또는 상단에 액션 바를 원하지 않는 경우

android:theme="@style/Theme.AppCompat.NoActionBar">

더 많은 정보 @

http://developer.android.com/guide/topics/ui/actionbar.html

편집하다:

게시물을 잘못 읽었을 수 있습니다.

op가 활동 테마가있는 대화 상자를 원합니다. 그래서 이미 Bobbake4 제안은 확장 Activity대신 ActionBarActivity.

아래 링크에서 @ Dialog Attributes도 살펴보십시오.

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/frameworks/base/core/res/res/values/themes.xml/


이것은 나를 위해 일했으며 방금 변경했습니다.

final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

이에:

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

내 테마가 AppCompat테마이고 내 활동이 AppCompatActivity(또는 Activity다른 사람의 답변에 제안 된대로) 인 경우에도이 문제가 발생했습니다 . 그래서 저는 프로젝트를 청소하고 다시 빌드하고 다시 실행했습니다.

( Build-> Clean Project; Build-> Rebuild Project; Run-> Run )

멍청 해 보일지 모르지만 이제는 훌륭하게 작동합니다 !

도움이되기를 바랍니다!


이것이 나를 위해 수정 한 것입니다. 매니페스트에 테마를 지정하는 대신 onCreate확장되는 각 활동 대해 정의했습니다 ActionBarActivity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.MyAppTheme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity_layout);
...
}

다음 MyAppTheme은의 하위 항목이며 Theme.AppCompatxml에 정의되어 있습니다. 테마는 super.onCreate이전에 설정해야합니다 setContentView.


당신의 스타일로 가서 부모를

parent="Theme.AppCompat"

대신에

parent="@android:style/Theme.Holo.Light"

제 경우에는 res 디렉토리에 values-v21 파일이 없습니다. 그런 다음 그것을 만들고 다음 코드를 추가했습니다.

  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

ActionBarActivity를 확장해야하는 경우 style.xml에 필요합니다.

<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base"/>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->

당신이 안드로이드와 같은 응용 프로그램의 메인 테마로 설정 한 경우 : 대신 Theme.Material.Light AppTheme.Base 다음은 "IllegalStateException이을 : 당신은이 활동과 Theme.AppCompat 테마 (또는 자손)를 사용합니다"얻을 것이다 오류입니다.


원하는 활동의 테마를 변경합니다. 이것은 나를 위해 작동합니다.

<activity
            android:name="HomeActivity"
            android:screenOrientation="landscape"
            android:theme="@style/Theme.AppCompat.Light"
            android:windowSoftInputMode="stateHidden" />

활동이 Theme.AppCompat을 사용했지만 삼성 장치 에서 그러한 충돌이 발생했습니다 . 근본 원인은 삼성 측의 이상한 최적화와 관련이 있습니다.

- if one activity of your app has theme not inherited from Theme.AppCompat
- and it has also `android:launchMode="singleTask"`
- then all the activities that are launched from it will share the same Theme

내 솔루션은 android:launchMode="singleTask"


나는 같은 문제가 있었지만 이것을 매니페스트에 넣으면 해결되었습니다 .android : theme = "@ style / Theme.AppCompat.

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name_test"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat">

        ...    

    </application>

그냥 해

new AlertDialog.Builder(this)

대신에

new AlertDialog.Builder(getApplicationContext())

나를 위해 ContextThemeWrapper를 사용하는 솔루션이었습니다.

private FloatingActionButton getFAB() {
Context context = new android.support.v7.view.ContextThemeWrapper(getContext(), R.style.AppTheme);
FloatingActionButton fab = new FloatingActionButton(context);
return fab;}

에서 안드로이드 - 프로그래밍 방식으로 FAB을 만드는 방법?


<android:theme="@android:style/Theme.Dialog">appWidget 에서 대화 상자를 표시하는 데 사용되는 테마가있는 활동이 있었고 동일한 문제가 발생했습니다.

다음과 같이 활동 코드를 변경하여이 오류를 해결했습니다.

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_AppCompat_Dialog); //this line i added
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dialog);
}

나는이 문제도 있었고 그것을 고치기 위해 한 일도 있었지만 여전히 Holo 테마를 사용하여 다음 단계를 수행했습니다.

먼저이 가져 오기를 대체했습니다.

import android.support.v7.app.AppCompatActivity;

이것으로 :

import android.app.Activity;

그런 다음 내 확장을 다음에서 변경했습니다.

public class MyClass extends AppCompatActivity {//...

이에:

public class MyClass extends Activity {//...

또한이 가져 오기를 변경해야했습니다.

import android.support.v7.app.AlertDialog;

이 가져 오기에 :

import android.app.AlertDialog;

그런 다음 활동 수준의 매니페스트에서 테마 태그를 사용할 수 있습니다.

android:theme="@android:style/Theme.Holo.Dialog" />

마지막으로 (v7 appCompat을 사용해야하는 프로젝트에 다른 클래스가없는 경우) 프로젝트를 정리하고 다시 빌드하거나 앱 수준의 gradle 빌드 파일에서이 항목을 삭제할 수 있습니다.

compile 'com.android.support:appcompat-v7:23.2.1'

if you have other classes in your project that has to use v7 appCompat then just clean and rebuild the project.


In my case such issue was appear when i tried to show Dialog. The problem was in context, I've use getBaseContext() which theoretically should return Activity context, but appears its not, or it return context before any Theme applied.

So I just replaced getBaseContexts() with "this", and now it work as expected.

        Dialog.showAlert(this, title, message,....);

You have came to this because you want to apply Material Design in your theme style in previous sdk versions to 21. ActionBarActivity requires AppThemeso if you also want to prevent your own customization about your AppTheme, only you have to change in your styles.xml (previous to sdk 21) so this way, can inherit for an App Compat theme.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

for this:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Change your theme style parent to

 parent="Theme.AppCompat"

This worked for me ...


You have many solutions to that error.

  1. You should use Activity or FragmentActivity instead of ActionbarActivity or AppCompatActivity

  2. If you want use ActionbarActivity or AppCompatActivity, you should change in styles.xml Theme.Holo.xxxx to Theme.AppCompat.Light (if necessary add to DarkActionbar)

If you don't need advanced attributes about action bar or AppCompat you don't need to use Actionbar or AppCompat.


In Android manifest just change theme of activity to AppTheme as follow code snippet

<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:theme="@style/AppTheme">
</activity>

This is when you want a AlertDialog in a Fragment

            AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
            adb.setTitle("My alert Dialogue \n");
            adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                  //some code

            } });
            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                 dialog.dismiss();

                } });
            adb.show();

In my experiences the problem was the context where I showed my dialog. Inside a button click I instantiate an AlertDialog in this way:

builder = new AlertDialog.Builder(getApplicationContext());

But the context was not correct and caused the error. I've changed it using the application context in this way:

In declare section:

Context mContext;

in the onCreate method

mContext = this;

And finally in the code where I need the AlertDialog:

start_stop = (Button) findViewById(R.id.start_stop);
start_stop.setOnClickListener( new View.OnClickListener()
     {
                @Override
                public void onClick(View v)
                {
                    if (!is_running)
                    {
                        builder = new AlertDialog.Builder(mContext);
                        builder.setMessage("MYTEXT")
                                .setCancelable(false)
                                .setPositiveButton("SI", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                    Task_Started = false;
                                    startTask();
                                    }
                                })
                                .setNegativeButton("NO",
                                        new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
            }
        }

This is the solution for me.


This one worked for me:

<application
           android:allowBackup="true"
           android:icon="@mipmap/ic_launcher"
           android:label="@string/app_name"
           android:theme="@style/AppTheme" >
           <activity
               android:name=".MainActivity"
               android:label="@string/app_name"
               android:theme="@style/Theme.AppCompat.NoActionBar">

               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />

                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>
</application>

Your Activity is extending ActionBarActivity which requires the AppCompat.theme to be applied. Change from ActionBarActivity to Activity or FragmentActivity, it will solve the problem.

If you use no Action bar then :

android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" 

Quick solution.

Change your base theme parent in styles.xml

Replace from

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

<style name="AppTheme" parent="Theme.AppCompat">

This solution worked for me.

Design library depends on the Support v4 and AppCompat Support Libraries, so don't use different version for appcompat and design library in gradle.

use

 compile 'com.android.support:appcompat-v7:23.0.0'
 compile 'com.android.support:design:23.0.0'

instead of

 compile 'com.android.support:appcompat-v7:23.0.0'
 compile 'com.android.support:design:23.1.0'

I was getting this same problem. Because i was creating custom navigation drawer. But i forget to mention theme in my manifest like this

android:theme="@style/Theme.AppCompat.NoActionBar"

As soon i added the above the theme to my manifest it resolved the problem.


For me none of the above answers worked even after I had Theme.AppCompat as my base theme for the application. I was using com.android.support:design:24.1.0 So I just changed the version to 24.1.1. After the gradle sync, Its working again and the exception went away. Seems to me the issue was with some older versions of design support libraries.

Just putting this here in case other answers don't work for some people.

참고URL : https://stackoverflow.com/questions/21814825/you-need-to-use-a-theme-appcompat-theme-or-descendant-with-this-activity

반응형