简体   繁体   中英

Custom dialog in android not working

I have to implement a custom dialog in my application, But my codes seems not working. Please help me.

Thanks in advance.

This is my code:

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.custom_dialog);
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.android);

And this is 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"
              >
    <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>

您可以尝试使用dialog.Show()

Instead of using setContentView() , get the LayoutInflater, the=n do whatever you want to do with the layout, then add it to the dialog using setView() method.

Because in case of AlertDialog, setContentView will not work.

For more information see this link

I would insist not to use getApplicationContext() to create the Dialog instance rather use Activitys instance to create it.

Dialog dialog = new Dialog(Activity_Name.this);

Also make sure you are calling dialog.show(); after creating your Dialog.

Dialog listDialog = new Dialog(this);
listDialog.setTitle(getString(R.string.picktemplate));
LayoutInflater li = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.custom_dialog, null, false);
listDialog.setContentView(view);
listDialog.setCancelable(true);

Button list1 = (Button) listDialog.findViewById(R.id.btnList);
listDialog.show();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM