Dialog crashing the app

和自甴很熟 提交于 2019-12-13 06:18:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!