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

前端 未结 14 840
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:28
    getSupportActionBar().getThemedContext()
    
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(getSupportActionBar().getThemedContext(), android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(getSupportActionBar().getThemedContext());
    }
    builder.setTitle("Alert Dialog")
           .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
    
                }
            })
           .setIcon(android.R.drawable.ic_dialog_alert)
           .show();
    
    0 讨论(0)
  • 2020-11-27 16:30

    In kotlin this worked to me:

    val dialog = AlertDialog.Builder(this)
    
    0 讨论(0)
  • 2020-11-27 16:33

    Basically your Activity is using Toolbar (which replaces Action Bar) so you need to use style for the Activity that has no Action Bar like Theme.AppCompat.Light.NoActionBar. If you have your own style for dialog then you need to inherit the proper AppCompat theme.

    <style name="myDialog" parent="Theme.AppCompat.Dialog">
        <item name="android:windowNoTitle">true</item>
        ...
    </style>
    

    AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.myDialog));
    
    0 讨论(0)
  • 2020-11-27 16:36

    The probem is because of Context which You are passing to build the Alert Dialog.Don't Use getApplicationContext().Try using your Activity context.Use AlertDialog.Builder builder = new AlertDialog.Builder(MainActiviy.this);

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

    This work for me... after read several answer was...

    Change my import like this:

    import android.app.AlertDialog;
    

    instead of

    import android.support.v7.app.AlertDialog; 
    

    this give error Unable to add window -- token null is not for an application... so I change the context of the builder from

    AlertDialog.Builder builder = new 
    

    AlertDialog.Builder(getAplicationContext()); to

    AlertDialog.Builder builder = new AlertDialog.Builder(*MainActivity.this*);
    
    0 讨论(0)
  • 2020-11-27 16:38

    You need to pass your Activity's context instead to pass your Context. Try with "this" instead "context". This work for me

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