This is the XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:gravity="center" android:text="Your total is 0" android:textSize="20dp" /> <Button android:id="@+id/button2" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button1" android:layout_centerVertical="true" android:text="Subtract one" android:textSize="20dp" /> <Button android:id="@+id/button1" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="62dp" android:text="Add one" android:textSize="20dp" />
This is the java code:
package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } int counter; Button add, sub; TextView display; @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); counter = 0; add = (Button) findViewById(R.id.button1); sub = (Button) findViewById(R.id.button2); display = (TextView) findViewById(R.id.textView1); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub counter++; display.setText("Your total is " + counter); } }); sub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub counter--; display.setText("Your total is " + counter); } }); return true; } }
When I click the buttons, nothing happens with the text of the text.
Please, help. I want the display to show the counter value after adding or subtracting, depending on which button was pressed.
source share