Error expanding layout to alertdialog (Android)
•
Android
public void popInstructionsDialog(String title, String text, String buttonText, Activity activity){
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = activity.getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.instructions, (ViewGroup) activity.findViewById(R.id.layout_root));
TextView text1 = (TextView) layout.findViewById(R.id.text);
text1.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show();
}
I received the following error
06-01 10:59:20.908: ERROR/AndroidRuntime(664): FATAL EXCEPTION: main
06-01 10:59:20.908: ERROR/AndroidRuntime(664): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
06-01 10:59:20.908: ERROR/AndroidRuntime(664): at android.view.ViewRoot.setView(ViewRoot.java:531)
06-01 10:59:20.908: ERROR/AndroidRuntime(664): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
06-01 10:59:20.908: ERROR/AndroidRuntime(664): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
06-01 10:59:20.908: ERROR/AndroidRuntime(664): at android.app.Dialog.show(Dialog.java:241)
06-01 10:59:20.908: ERROR/AndroidRuntime(664): at hiit.nopsa.pirate.InstructionDialog.popInstructionsDialog(InstructionDialog.java:34)
Instructiondialog. Java: 34 is the last line of code "alertdialog. Show()". Anyone can advise me how to correct this problem. Here are instructions.xml
<?xml version="1.0" encoding="utf-8"?>
<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/title"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
resolvent:
Make mcontext public and set try
mContext =this in oncreate method
And use it when using alertdialog... I have been hit by this problem many times... The only solution I use to solve this problem is this
I hope this can help
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码