【发布时间】:2013-05-10 01:40:15
【问题描述】:
我希望这不是一个愚蠢的问题。我在清除 TextView 时遇到了一些麻烦。我环顾四周,每个人都在说 use: textView.setText("");在 onCreate 但由于某种原因似乎不起作用。基本上,我的应用程序只接受来自 editText 的数字,然后运行斐波那契数列(单击按钮时)并在 textView 中显示结果。好吧,序列显示正常,但我希望每次单击按钮时都清除文本视图 - 到目前为止,它只是不断向已经存在的内容添加更多文本。
我是在放置 textView.setText("");在错误的位置?还是我只是错过了其他一些概念? (我也尝试从我的 OnClick 中放置它 - 这也不起作用)。
这是我的代码:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
String array = fibList.toString();
textView.setText(array);
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
【问题讨论】:
-
你应该在
onClick(View v)里面添加textView.setText(""); -
@dave 只是想知道您是否尝试过我的答案,我看到您尝试了其他答案。
-
我做的问题是清除我的数组列表然后清除 textView。谢谢。
-
请注意,在三星 Galaxy 上,必须设置一个 textView 的 inputType 字段(我设置 inputType = text)才能执行 setText("") 或 setText(null)