[英]Trying to generate dialog with 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>
我需要怎么做才能使我的按鈕顯示在對話框窗口中?
當您使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.