如何从android中的edittext获取文本?

时间:2010-06-19 10:19:51

标签: android

我使用以下代码从文本框中获取值。但是它不起作用它会给出异常并强制关闭。如何获取文本框的值?任何人都可以帮助我吗?

public class alertwithlogin extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    showDialog(1);
}
@Override
protected Dialog onCreateDialog(int id) {
  LayoutInflater factory = LayoutInflater.from(this); 
     final View textEntryView = factory.inflate(R.layout.alertedit, null); 
     return new AlertDialog.Builder(alertwithlogin.this)             
         .setTitle(R.string.alert_dialog_text_entry)
         .setView(textEntryView)
         .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {
              EditText edittext = (EditText) findViewById(R.id.username_edit); 
              Toast.makeText(getApplicationContext(),edittext.getText(),        Toast.LENGTH_SHORT).show();

             }
         })
         .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {                     
             }
         })
         .create();     
}

}

alertedit.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">
<TextView 
    android:id="@+id/username_view"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginLeft="20dip"
    android:layout_marginRight="20dip"
    android:text="@string/alert_dialog_username"
    android:gravity="left"
    android:textAppearance="?android:attr/textAppearanceMedium" />            
<EditText
    android:id="@+id/username_edit"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_marginLeft="20dip"
    android:layout_marginRight="20dip"
    android:scrollHorizontally="true"
    android:autoText="false"
    android:capitalize="none"
    android:gravity="fill_horizontal"
    android:textAppearance="?android:attr/textAppearanceMedium" />        
</LinearLayout>

1 个答案:

答案 0 :(得分:4)

您对findViewByID的调用返回null,因为它在您的Activity上调用,并且该布局不包含具有该ID的项目。由于您不检查edittext是否为null,因此对getText()强制的调用将关闭。

如果替换:

EditText edittext = (EditText) findViewById(R.id.username_edit);

由:

EditText edittext = (EditText) textEntryView.findViewById(R.id.username_edit);

您可以在textEntryView(用于创建对话框)中进行搜索,并且可以正常工作。