Sha*_*amy 0 android android-layout
我是android的新手.我已经为两个整数的Sum编写了代码.我收到NULLPointerException.findViewById()方法返回null.有人可以帮我修复错误.
<EditText
android:id="@+id/firstInt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:hint="@string/InputHint"
/>
<EditText
android:id="@+id/secondInt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:hint="@string/InputHint"
/>
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Result"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:textSize="18dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add"
android:layout_gravity="center"
android:onClick="calculateAdd"/>
Run Code Online (Sandbox Code Playgroud)
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText e1 = (EditText)findViewById(R.id.firstInt);
EditText e2 = (EditText)findViewById(R.id.secondInt);
TextView tv = (TextView)findViewById(R.id.result);
}
public void calculateAdd(View view){
int x = Integer.parseInt(e1.getText().toString());
int y = Integer.parseInt(e2.getText().toString());
int z = x + y;
tv.setText(z);
}
Run Code Online (Sandbox Code Playgroud)
这是我编写的一个非常简单的程序.但是,面对这个问题.
我的堆栈跟踪错误:
java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
Run Code Online (Sandbox Code Playgroud)
您只是声明方法EditText范围内部onCreate().
EditText e1, e2;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.firstInt);
e2 = (EditText)findViewById(R.id.secondInt);
tv = (TextView)findViewById(R.id.result);
}
public void calculateAdd(View view){
int x = Integer.parseInt(e1.getText().toString());
int y = Integer.parseInt(e2.getText().toString());
int z = x + y;
tv.setText(z);
}
Run Code Online (Sandbox Code Playgroud)
愿这对你有所帮助.
如果您需要更多信息请参考此链接/sf/answers/3618174031/
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |