我正在尝试在TextView或EditText上显示计算结果。我从one100lbs和tenPounds获取用户输入,然后将其相加,并尝试在totalPounds上显示它。这不是我要使用的等式,只是想看看它是否有效。当前使用下面的代码,我的应用程序崩溃了。这一切都在一个activity之下。另外,当我更改EditText的ID时,为什么editText在relative layout上的位置也会发生变化?请没有链接,我知道这很简单,但我是一个菜鸟。我已经找过了,现在很难找到解决方案。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pounds);
addListenerOnSpinnerItemSelection();
EditText one100lbs = (EditText) findViewById(R.id.one100lbs);
int one = Integer.valueOf(one100lbs.getText().toString());
EditText tenPounds = (EditText) findViewById(R.id.tenPounds);
int two = Integer.valueOf(tenPounds.getText().toString());
int result = one + two;
TextView textView = (TextView) findViewById(R.id.totalPounds);
textView.setText(result);
}发布于 2013-01-15 07:38:32
你想要这样的东西:
textView.setText(String.valueOf(result));现在,当你只提供一个int类型的时候,Android正在尝试寻找一个资源id,这将会失败。
我还发现你在使用EditTexts,除了forcing the keypad to be only numbers之外,你还可以这样做:
int one = 0;
int two = 0;
try{
EditText one100lbs = (EditText) findViewById(R.id.one100lbs);
one = Integer.valueOf(one100lbs.getText().toString().trim());
}
catch (NumberFormatException e)
{
one = -1;
}
try{
EditText tenPounds = (EditText) findViewById(R.id.tenPounds);
two = Integer.valueOf(tenPounds.getText().toString().trim());
}
catch (NumberFormatException e)
{
two = -1;
}
int result = one + two;
TextView textView = (TextView) findViewById(R.id.totalPounds);
textView.setText(String.valueOf(result)); 发布于 2013-01-15 08:18:51
您可以使用以下任一选项:
textView.setText(Integer.toString(result));或
textView.setText(result + "");https://stackoverflow.com/questions/14328780
复制相似问题