如何让TextView或EditText显示变量

时间:2013-01-14 23:35:51

标签: android

我正在尝试在TextViewEditText上显示计算结果。我从one100lbs和tenPounds中获取用户输入,然后将其添加到一起,并尝试在totalPounds上显示它。它不是我将使用的等式,但只是想看到它的工作原理。目前使用下面的代码我的应用程序崩溃。这一切都在activity之下。另外,当我在EditText上更改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);   
}

2 个答案:

答案 0 :(得分:4)

你想要这样的东西:

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)); 

答案 1 :(得分:0)

您可以使用以下任一项:

textView.setText(Integer.toString(result));

textView.setText(result + "");