Reputation: 579
Im trying yo implement a counter. There will be a place to show the count, and 2 buttons (++ & --).
<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" />
But it is not working. Im very new in Android and I dont get to see what im doing wrong.
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);
}
}
When I run the app, it stops suddenly (unexpectly) when I click for the second time. Can anyone give a little help? thanks for your time!
Upvotes: 2
Views: 1816
Reputation: 133560
texto.setText(n);
This is your mistake. n
is an int values. setText looks for a resource with the id. if not found you get ResourceNotFoundException
.
You are using this public final void setText (int resid)
instead of public final void setText (CharSequence text)
http://developer.android.com/reference/android/widget/TextView.html
Change to
texto.setText(String.valueOf(n));
Also
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
Although casting edittext to textview is not a problem i suggest you change to texto = (EditText) findViewById(R.id.Edittext1);
There is no need to initialize edittext everytime on button click.
Also remove implements OnClickListener
coz you have android:onClick="onClick"
Upvotes: 3