gpt4 book ai didi

android - 在Android中实现一个简单的计数器

转载 作者:搜寻专家 更新时间:2023-11-01 08:53:18 24 4
gpt4 key购买 nike

我正在尝试实现一个计数器。将有一个显示计数的地方,以及 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com