2011-10-11 146 views
0

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

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> 

任何想法?

+0

你能不能给我们logcat的输出? –

回答

2

您拥有的EditText在XML的对话框的布局......和你正确使用findViewById()来实例化的TextView ...

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

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

有些东西与输入框对象有关。你用这种方法创建它,但是我没有看到你实际上在任何地方添加了布局。此方法完成后,您将显示对话框,但输入框不会显示在任何位置。实际上,我认为inputBox可能是垃圾收集的,因为getName()方法完成后没有引用。因此,当你调用获取输入时,它可能为空。

我想你的意思做的是这样的:

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