尝试阅读自定义对话框中的编辑框...获取FC

时间:2011-10-11 19:09:53

标签: android

我正在尝试读取EditText框并将其内容发送到自定义对话框中的另一个方法。我当前的代码会导致强制关闭。 logcat非常含糊......但是我知道在这种方法中发生了未捕获的异常:

public void getName(){

         Dialog dialog = new Dialog(main.this);
         dialog.setContentView(R.layout.customdialog);
         dialog.setTitle("New Game");
         dialog.setCancelable(true);
         //there are a lot of settings, for dialog, check them all out!
         final EditText inputBox = new EditText(this);

         //set up text
         final TextView text = (TextView) dialog.findViewById(R.id.TextView01);
         text.setText("Enter Your Name...");


         //set up button
         final Button button = (Button) dialog.findViewById(R.id.namebutton);
         button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             String str = inputBox.getText().toString(); 
             setName(str);
        }
         });
         //now that the dialog is set up, it's time to show it    
         dialog.show();
     }

这是自定义XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content" android:layout_height="wrap_content">
 <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/linearLayout1">
     <TextView android:text="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/nameprompt"></TextView>
     <EditText android:layout_width="fill_parent" android:id="@+id/editText1" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="Player">
         <requestFocus></requestFocus>
     </EditText>
     <Button android:layout_height="wrap_content" android:id="@+id/namebutton" android:text="Ok" android:layout_width="fill_parent"></Button>
 </LinearLayout>

</RelativeLayout>

任何想法???

2 个答案:

答案 0 :(得分:2)

您的XML中有EditText用于Dialog的布局......并且您正在使用findViewById()来实例化TextView ...

你需要为EditText做同样的事情,也可以使用findViewById()来实例化它。

final EditText inputBox = (EditText) dialog.findViewById(R.id.editText1);

答案 1 :(得分:1)

inputBox对象出现了问题。您可以在此方法中创建它,但我没有看到您实际上在任何地方添加到布局。此方法完成后,您将显示对话框,但输入框不会显示在任何位置。实际上,我认为inputBox可能是垃圾收集的,因为在getName()方法完成后没有引用if。因此,当您调用get输入时,它可能为null。

我认为你的意思是:

final EditText inputBox = (EditText)dialog.findViewById(R.id.editText1)