You need to use a Theme.AppCompat theme (or descendant) with this activity. Change to Theme.AppCompat causes other error

前端 未结 14 838
Happy的楠姐
Happy的楠姐 2020-11-27 15:47

I use appcompat v22.1.0 in my App and use Toolbar. Everything was fine when I use Theme.AppCompat.Light.NoActionBar. When I start implement AlertDialog

相关标签:
14条回答
  • 2020-11-27 16:17

    Saw this same exception using Activity and Theme.Light theme. My problem was a wrong import, I was using the support one. import android.support.v7.app.AlertDialog; instead of import android.app.AlertDialog;

    0 讨论(0)
  • 2020-11-27 16:19

    In my case, this crash was caused because I was passing View.getContext().getApplicationContext() as Context to the Builder. This was fixed by using getActivity() instead.

    0 讨论(0)
  • 2020-11-27 16:23

    Adding Android:theme="@style/Theme.AppCompat" like this in manifest

    <activity
        android:theme="@style/Theme.AppCompat"
        android:name=".MainActivity"
    

    solved the problem

    0 讨论(0)
  • 2020-11-27 16:24

    if you have this error when you creating a dialog (just in my case) you should use the following:

    AlertDialog.Builder dialog = new AlertDialog.Builder(context, R.style.Theme_AppCompat_Light);
    

    instead of:

    AlertDialog.Builder dialog = new AlertDialog.Builder(context);
    

    This worked me perfectly!

    0 讨论(0)
  • 2020-11-27 16:27

    Fixed my problem by using MainActivity.this (or YourActivityName.this)

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
    

    Make sure you already Theme.AppCompat and extending AppCompatActivity.

    0 讨论(0)
  • 2020-11-27 16:28

    If you are using support library your activity extends AppCompactActivity, if you use android studio to create activity this is default. In such case pass context to the builder as ActivityName.this or simply this if you are passing it in onCreate, passing getApplicationContext() will not work.

    This is my style using appcompact

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="android:textSize">18sp</item>
        </style>
    
        <style name="AppTheme.NoActionBar">
            <item name="windowActionBar">false</item>
            <item name="windowNoTitle">true</item>
        </style>
    

    And everything is working fine when I use this or ActivityName.this as mentioned above (here ActivityName is the name of your current activity i.e. MainActivity.this).

    If you are using in fragment you should pass getActivity() as context to builder instead of getContext().

    0 讨论(0)
提交回复
热议问题