Alert dialog with custom layout error

So this is related to the question I asked earlier. I am trying to display a warning using the specified layout. My layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout> 

And the code to call and display the warning dialog:

  Context mContext = getApplicationContext(); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); // use a custom View defined in xml View view = LayoutInflater.from(mContext).inflate(R.layout.sell_dialog, (ViewGroup) findViewById(R.id.layout_root)); builder.setView(view); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do whatever you want with the input } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); 

When I run it, I get an error message:

Untrained handler: main thread due to an uncaught exception android.view.WindowManager $ NadTokenException: Unable to add window - null token is not for application

I looked at the Android development site and can't figure it out. I think I just missed something obvious, but the fix does not jump on me. How can I open this warning dialog?

+4
source share
1 answer

Do not use getApplicationContext() . This method is only available on Context (e.g. Activity ) - use Context for AlertDialog.Builder .

Here is an example project from one of my books that, among other things, shows an AlertDialog based on a custom View .

+9
source

Source: https://habr.com/ru/post/1308516/


All Articles