问题
Ok just to know,I copy-pasted the code from the android website,so I don't think there is something wrong.
The problem is that when I press the button it crashes.And it crashes from the dialog code,because I don't have anything else there.
The code is:
MainDialog.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"
>
<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>
And on the case that button1 is pressed:
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.maindialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
dialog.show();
回答1:
You use the Activity context and add a call to dialog.show();:
Context mContext = this; //Assumes you are calling this from within an activity
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.maindialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.icon);
dialog.show();
来源:https://stackoverflow.com/questions/7956827/dialog-crashing-the-app