2011-11-01 70 views
1

任何人都知道为什么我的按钮没有显示在对话窗口中?试图与android生成对话框

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(); 

这是我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> 

什么我需要在对话窗口中这样做我的按钮节目吗?

+0

你应该告诉日志在崩溃时说什么,它通常解释很多。 – Lycha

回答

1

当您使用findViewById()时,您的对话框不可见,这意味着具有该ID的视图尚未处于视图层级中并且无法找到。这导致error beeing null,这将在以下行中引发NullPointerException

您可以通过单独膨胀布局并在充气图上使用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(); 
+0

谢谢,任何想法为什么如果我添加一个按钮,它不会显示在对话框中?我已经调整了我的代码以反映它。 –

+0

如果您将其添加到布局XML中?应该在理论上工作。你的'LinearLayout'被设置为水平方向,也许它是不可见的,因为它被渲染在屏幕之外*(取决于TextView宽度)*。尝试将其设置为垂直。除此之外,我没有看到更新后的布局/代码就无法分辨。如果找不到问题并包含更新后的布局/代码,请打开一个新问题。 – 2011-11-01 01:43:09

+0

添加:行动,不应该在这里上午3点。没有看到您的更新代码。猜猜它是像上面描述的那样呈现的,XML通常看起来很好。 – 2011-11-01 01:50:10