在我的 Android 项目中按 Enter 时出现 NullPointerException。我用谷歌搜索,人们遇到了同样的问题,因为他们没有设置 findViewByIt。不幸的是我明白了。发生了什么事 - 为什么我有异常?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
textPassword = (EditText) findViewById(R.id.editText1);
buttonLogin = (Button) findViewById(R.id.button1);
buttonLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
PrintToast(textPassword.getText().toString());
}
});
textPassword.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
try
{
if ((event.getAction() == KeyEvent.ACTION_DOWN))
{
buttonLogin.performClick();
}
}
catch ( Exception e) {
PrintToast(e.toString());
}
return false;
}
});
}
布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:gravity="top"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainPage" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="@string/PIN_label_HelloMsg"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="@string/PIN_button_AcceptPIN" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:text="@string/PIN_label_EnterPIN"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
</EditText>
</RelativeLayout>