TextViews in Android

TextView is a text field, usually user editable. You can read and write TextView values from code. You often have to cast between CharSequence, String, int and other types.
Prequisites: Android Hello World Explained

Read TextView

final TextView q = (TextView) findViewById(R.id.q);
String s = q.getText().toString();

Write TextView

out.setText("Foo bar");

Numbers have to be cast to string.

int x = 2;
out.setText(String.valueOf(x*x));

Area Calculator with TextView

private void calculate() {
      final TextView q = (TextView) findViewById(R.id.q);
      final TextView out = (TextView) findViewById(R.id.out);
      String s = q.getText().toString();
      int x=0;
      try {
            x = Integer.parseInt(s);
      } catch (NumberFormatException e) { }
      out.setText(String.valueOf(x*x));
}
Posted in Uncategorized | Tagged , , , , , | Comments Off on TextViews in Android

Comments are closed.