我正在尝试使用新窗口并附加edittext以从用户获取名称。当它命中“”名称“ .getText() .toString()”
时,它总是会失败这是我的主要
public class chatter extends Activity {
private String name;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.setNameMenu:
setname();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void setname()
{
final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
/*Dialog dialog = new Dialog(chatter.this);
dialog.setTitle("This is my custom dialog box");
*/
setContentView(R.layout.custom_dialog);
//dialog.setCancelable(true);
Button button = (Button) findViewById(R.id.submitNameButton);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//String nameinput = textNameInput.getText().toString();
**//this is where it does not work**
**Editable debug1 = textNameInput.getText();**
String nameinput = debug1.toString();
name = nameinput;
finish();
}
});
}
}
这是布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<TextView
android:id="@+id/dialogueText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="please input your name:"
/>
<EditText
android:id="@+id/nameBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/dialogueText" />
<Button
android:text=" Set "
android:id="@+id/submitNameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/nameBox"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
我是Android新手编程的新手,请解释出错的地方。
答案 0 :(得分:1)
在致电final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
setContentView(R.layout.custom_dialog);
答案 1 :(得分:1)
由于您没有发布堆栈跟踪,我猜错了,但我认为您的NullPointerException
textNameInput
为null
R.layout.custom_dialog
。您还没有说过您在代码中引用的两个布局中的哪一个是您列出的布局,但我猜它是findViewById(R.id.nameBox)
?如果是这样,那么在加载包含null
的布局之前,您对R.id.nameBox
的调用将返回{{1}}。加载布局后将呼叫移至。