简体   繁体   English

尝试使用Android生成对话框

[英]Trying to generate dialog with android

Anyone know why my button isn't showing up in the dialog window? 有人知道为什么我的按钮没有显示在对话框窗口中吗?

    Dialog d = new Dialog(AddContact.this);

    LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
    ViewGroup contentView = (ViewGroup) li.inflate(R.layout.dialog,null);

    d.setContentView(contentView);
    d.setTitle("Please correct these errors:");

    TextView error = (TextView) contentView.findViewById(R.id.textView1);
    Button closer = (Button) contentView.findViewById(R.id.button1);

    closer.setText("Close");
    error.setText(errorMessage);
    d.show();

This my dialog.xml layout file: 这是我的dialog.xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:orientation="vertical" android:padding="5dp">

    <TextView android:text="TextView" android:id="@+id/textView1"
        android:layout_height="fill_parent" android:layout_width="fill_parent" />

    <Button android:text="Button" android:id="@+id/button1"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:gravity="center" />

</LinearLayout>

What do I need to do so my button shows in the dialog window? 我需要怎么做才能使我的按钮显示在对话框窗口中?

Your dialog is not visible when you use findViewById() , which means that the view with that id is not yet in your view hierachy and can not be found. 当您使用findViewById() ,您的对话框不可见,这意味着具有该ID的视图尚未出现在您的视图层次结构中,并且无法找到。 This results in error beeing null , which will throw a NullPointerException in the following line. 这将导致error beeing为null ,这将在下一行中引发NullPointerException

You can solve this by inflating the layout seperately and use findViewById() on the inflated view. 您可以通过分别扩大布局并在扩大后的视图上使用findViewById()来解决此问题。

Dialog d = new Dialog(AddContact.this);
LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
ViewGroup contentView = (ViewGroup)  li.inflate(R.layout.dialog, null);
d.setContentView(contentView);
d.setTitle("Please correct these errors:");
error = (TextView) contentView.findViewById(R.id.textView1);
error.setText(errorMessage);
d.show();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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