我正在尝试实现一个计数器。将有一个地方显示计数,以及 2 个按钮(++ 和 --)。
<EditText
android:id="@+id/Edittext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:text="@string/cero" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/Edittext1"
android:layout_below="@+id/Edittext1"
android:layout_marginTop="16dp"
android:onClick="onClick"
android:text="@string/mas" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:layout_marginTop="16dp"
android:onClick="onClick"
android:text="@string/menos" />
但是它不起作用。我对 Android 很陌生,我不知道自己做错了什么。
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//View boton1 = findViewById(R.id.button1);
//boton1.setOnClickListener(this);
//View boton2 = findViewById(R.id.button2);
//boton2.setOnClickListener(this);
}
@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;
}
@Override
public void onClick(View v) {
TextView texto = (TextView) findViewById(R.id.Edittext1);
int n = Integer.parseInt(texto.getText().toString());
switch(v.getId())
{
case R.id.button1: texto.setText("case1");
n++;
break;
case R.id.button2: texto.setText("case2");
n--;
break;
default: texto.setText("default");
}
texto.setText(n);
}
}
当我运行该应用程序时,当我第二次单击时,它突然(意外地)停止。 有人可以提供一点帮助吗?感谢您的宝贵时间!
最佳答案
texto.setText(n);
这是你的错误。 n
是一个 int 值。 setText 查找具有 id 的资源。如果没有找到,您将收到 ResourceNotFoundException
。
您正在使用此 public final void setText (int resid)
而不是 public final void setText (CharSequence text)
http://developer.android.com/reference/android/widget/TextView.html
更改为
texto.setText(String.valueOf(n));
还有
EditText text0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
texto = (EditText) findViewById(R.id.Edittext1);
http://developer.android.com/reference/android/widget/TextView.html
虽然将 edittext 转换为 textview 不是问题,但我建议您更改为 texto = (EditText) findViewById(R.id.Edittext1);
无需每次单击按钮时都初始化 edittext。
同时删除 implements OnClickListener
因为你有 android:onClick="onClick"
关于android - 在Android中实现一个简单的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21108126/