Hi i'm working on a Android Launcher that Shows Calculator activity. It shows the layout fine but does nothing when you click on any of the buttons I need help I have tried everything I can and i'm getting upset! any help would be amazing!!
Calculator.java:
package com.dva.schooltoolshome;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Calculator extends FragmentActivity implements OnClickListener {
private TextView calculatorDisplay;
private static final String DIGITS = "0123456789.";
private Boolean userIsInTheMiddleOfTypingANumber = false;
DecimalFormat df = new DecimalFormat("############");
CalculatorBrain brain;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
brain = new CalculatorBrain();
calculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
findViewById(R.id.buttonClearMemory).setOnClickListener(this);
findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonCos) != null) {
findViewById(R.id.buttonCos).setOnClickListener(this);
}
if (findViewById(R.id.buttonSin) != null) {
findViewById(R.id.buttonSin).setOnClickListener(this);
}
// Another way to hide the window title and actionbar, but only in newer sdk's
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// ActionBar actionBar = getActionBar();
// actionBar.setDisplayShowHomeEnabled(false);
// actionBar.setDisplayShowTitleEnabled(false);
// actionBar.hide();
// }
}
// #Override
public void onClick(View view) {
String buttonPressed = ((Button) view).getText().toString();
// String digits = "0123456789.";
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
calculatorDisplay.append(buttonPressed);
} else {
calculatorDisplay.setText(buttonPressed);
userIsInTheMiddleOfTypingANumber = true;
}
} else {
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
brain.setOperand(Double.parseDouble(calculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
brain.performOperation(buttonPressed);
calculatorDisplay.setText(df.format(brain.getResult()));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", brain.getResult());
outState.putDouble("MEMORY", brain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
brain.setOperand(savedInstanceState.getDouble("OPERAND"));
brain.setMemory(savedInstanceState.getDouble("MEMORY"));
calculatorDisplay.setText(df.format(brain.getResult()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
CalculatorBrain.java:
package com.dva.schooltoolshome;
public class CalculatorBrain {
// 3 + 6 = 9
// 3 & 6 are called the operand.
// The + is called the operator.
// 9 is the result of the operation.
private double operand = 0;
private double waitingOperand = 0;
private String waitingOperator = "";
private double calculatorMemory = 0;
public void setOperand(double operand) {
this.operand = operand;
}
public double getResult() {
return operand;
}
// used on screen orientation change
public void setMemory(double calculatorMemory) {
this.calculatorMemory = calculatorMemory;
}
// used on screen orientation change
public double getMemory() {
return calculatorMemory;
}
public String toString() {
return Double.toString(operand);
}
protected double performOperation(String operator) {
/*
* If you are using Java 7, then you can use switch in place of if statements
*
* switch (operator) {
* case "MC":
* calculatorMemory = 0;
* break;
* case "M+":
* calculatorMemory = calculatorMemory + operand;
* break;
* }
*/
if (operator.equals("MC")) {
calculatorMemory = 0;
} else if (operator.equals("M+")) {
calculatorMemory = calculatorMemory + operand;
} else if (operator.equals("M-")) {
calculatorMemory = calculatorMemory - operand;
} else if (operator.equals("MR")) {
operand = calculatorMemory;
} else if (operator.equals("C")) {
operand = 0;
waitingOperator = "";
waitingOperand = 0;
calculatorMemory = 0;
} else if (operator.equals("Sqrt")) {
operand = Math.sqrt(operand);
} else if (operator.equals("1/x")) {
if (operand != 0) {
operand = 1 / operand;
}
} else if (operator.equals("+/-")) {
operand = -operand;
} else if (operator.equals("sin")) {
operand = Math.sin(operand);
} else if (operator.equals("cos")) {
operand = Math.cos(operand);
} else {
performWaitingOperation();
waitingOperator = operator;
waitingOperand = operand;
}
return operand;
}
protected void performWaitingOperation() {
if (waitingOperator.equals("+")) {
operand = waitingOperand + operand;
} else if (waitingOperator.equals("*")) {
operand = waitingOperand * operand;
} else if (waitingOperator.equals("-")) {
operand = waitingOperand - operand;
} else if (waitingOperator.equals("/")) {
if (operand != 0) {
operand = waitingOperand / operand;
}
}
}
}
activity_calculator.xml:
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:maxLines="1"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1" >
<Button
android:id="#+id/buttonAddToMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="M+" />
<Button
android:id="#+id/buttonSubtractFromMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="M-" />
<Button
android:id="#+id/buttonRecallMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="MR" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout2" >
<Button
android:id="#+id/buttonClear"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="C" />
<Button
android:id="#+id/buttonToggleSign"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="+/-" />
<Button
android:id="#+id/buttonDivide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="/" />
<Button
android:id="#+id/buttonMultiply"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="*" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout3" >
<Button
android:id="#+id/button7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button7" />
<Button
android:id="#+id/button8"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button8" />
<Button
android:id="#+id/button9"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button9" />
<Button
android:id="#+id/buttonSubtract"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="-" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout4" >
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button4" />
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button5" />
<Button
android:id="#+id/button6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button6" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="+" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout5"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout7"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:text="#string/button1" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:text="#string/button2" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".34"
android:text="#string/button3" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button0"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".66"
android:text="#string/button0" />
<Button
android:id="#+id/buttonDecimalPoint"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".34"
android:text="." />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/buttonEquals"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".25"
android:text="=" />
</LinearLayout>
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/wbrowser"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/browser" />
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/wbrowser"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<Button
android:id="#+id/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ImageButton01"
android:layout_centerHorizontal="true"
android:text="Tools" />
<Button
android:id="#+id/buttonClearMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_above="#+id/ImageButton01"
android:layout_alignLeft="#+id/tools"
android:layout_marginBottom="163dp"
android:layout_weight=".25"
android:text="MC" />
</RelativeLayout>
I'm still new to android development so please don't judge
Regards
Rapsong11
First of all use switch statement in OnClick(View v) function for every button.
like this.
public void onClick(View v)
{
case R.Id.button1
// the functionality code goes here
break;
case R.id.button2
break;
}
Related
I don't understand why the app doesn't work when I launch it.
First of all, this is what I want:
Spaceship appears perfectly
And this is what appears when I launch the game:
Spaceship disappears!
I dont know what is wrong. I haven't an atribute which makes invisible the ImageView... Here is my code:
game_activity.xml (game design)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.spaceinvaders.GameActivity">
<ImageView
android:id="#+id/fondo_juego"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/fondo3" />
<ImageView
android:id="#+id/enemigo"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:src="#drawable/enemigodiseno11"/>
<Button
android:id="#+id/disparo"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#android:color/transparent"
android:onClick="dispara"
android:visibility="visible" />
<ImageView
android:id="#+id/municion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/disparo"
android:layout_centerHorizontal="true"
android:src="#drawable/municion"
android:visibility="invisible" />
<ImageView
android:id="#+id/nave"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:src="#drawable/diseno11" />
<Button
android:id="#+id/control_izquierda"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#android:color/transparent"
android:onClick="actualizaPosicion"
android:visibility="visible" />
<Button
android:id="#+id/control_derecha"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#android:color/transparent"
android:onClick="actualizaPosicion"
android:visibility="visible" />
</RelativeLayout>
activity_main.xml (This is the principal screen)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/principal_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.spaceinvaders.MainActivity">
<ImageView
android:id="#+id/fondo_pantalla_principal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/fondo2" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:adjustViewBounds="true"
android:src="#drawable/iconotitulo"
android:layout_centerHorizontal="true"/>
<ImageView
android:layout_width="130dp"
android:layout_height="130dp"
android:adjustViewBounds="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/iconotitulo1"/>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical">
<ImageButton
android:id="#+id/play_boton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:scaleType="centerCrop"
android:onClick="iniciaJuego"
android:src="#drawable/boton1" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_margin="10dp">
<ImageButton
android:id="#+id/opcion_boton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_centerHorizontal="true"
android:background="#android:color/transparent"
android:scaleType="centerCrop"
android:src="#drawable/boton2" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
popup_activity.xml (a simple popup which allow the user to change some parameters)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#839ceaac"
android:orientation="vertical">
<ImageButton
android:id="#+id/volver_boton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_marginRight="2dp"
android:layout_marginTop="3dp"
android:background="#android:color/transparent"
android:scaleType="centerCrop"
android:src="#drawable/cerrar" />
<TextView
android:id="#+id/titulo_opciones"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="6dp"
android:layout_marginTop="5dp"
android:text="Opciones gráficas"
android:textSize="20dp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_below="#id/titulo_opciones"
android:background="#9dc8a6" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/titulo_opciones"
android:layout_marginBottom="8dp"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:id="#+id/fondo_titulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:text="Fondo"
android:textSize="15sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/fondo_1"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/fondo_titulo"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaFondo"
android:scaleType="centerCrop"
android:src="#drawable/fondo" />
<ImageView
android:id="#+id/fondo_2"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/fondo_1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaFondo"
android:scaleType="centerCrop"
android:src="#drawable/fondo1" />
<ImageView
android:id="#+id/fondo_3"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/fondo_2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaFondo"
android:scaleType="centerCrop"
android:src="#drawable/fondo3" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:id="#+id/nave_titulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:text="Nave"
android:textSize="15sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/nave_1"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/nave_titulo"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaNave"
android:src="#drawable/diseno11" />
<ImageView
android:id="#+id/nave_2"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/nave_1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaNave"
android:src="#drawable/diseno21" />
<ImageView
android:id="#+id/nave_3"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/nave_2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaNave"
android:src="#drawable/diseno31" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:id="#+id/enemigos_titulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:text="Enemigos"
android:textSize="15sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/enemigo_1"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_below="#id/enemigos_titulo"
android:layout_centerHorizontal="true"
android:layout_marginBottom="3dp"
android:adjustViewBounds="true"
android:onClick="actualizaEnemigo"
android:rotation="180"
android:src="#drawable/enemigodiseno11" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
GameActivity.java (game_activity.xml functionality)
package com.example.android.spaceinvaders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class GameActivity extends AppCompatActivity {
ImageView municion;
ImageView nave;
ImageView fondoJuego;
ImageView enemigo;
Button botonDisparo;
Handler manejaDisparo = new Handler();
Handler manejaEnemigo = new Handler();
final int movimiento = 30;
final int movimientoEnemigo = 20;
boolean inicioAFin = false;
int ladeadoIzq, ladeadoDer, frontal, disparo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
municion = (ImageView) findViewById(R.id.municion);
nave = (ImageView) findViewById(R.id.nave);
enemigo = (ImageView) findViewById(R.id.enemigo);
fondoJuego = (ImageView) findViewById(R.id.fondo_juego);
botonDisparo = (Button) findViewById(R.id.disparo);
Intent i = getIntent();
if (i != null) {
String data = i.getStringExtra("arg");
introduceCambios(data);
}
manejaEnemigo.postDelayed(accionMovimiento, 0);
}
private void introduceCambios(String data) {
String[] info = data.split(" ");
int idFondo = getResources().getIdentifier(info[0], "drawable", getPackageName());
fondoJuego.setImageResource(idFondo);
int idNave = getResources().getIdentifier(info[1], "drawable", getPackageName());
cambiosMovilidad(idNave);
nave.setImageResource(frontal);
int idEnemigo = getResources().getIdentifier(info[2], "drawable", getPackageName());
enemigo.setImageResource(idEnemigo);
}
public void actualizaPosicion(View v) {
switch (v.getId()) {
case (R.id.control_derecha):
if (!seSale("der", "CU")) {
nave.setImageResource(ladeadoIzq);
nave.setX(nave.getX() - movimiento);
}
break;
case R.id.control_izquierda:
if (!seSale("izq", "CU")) {
nave.setImageResource(ladeadoDer);
nave.setX(nave.getX() + movimiento);
}
break;
}
}
private void cambiosMovilidad(int idNave) {
switch (idNave) {
case 2130837589:
frontal = R.drawable.diseno11;
ladeadoDer = R.drawable.diseno13;
ladeadoIzq = R.drawable.diseno12;
disparo = R.drawable.municion;
break;
case 2130837592:
frontal = R.drawable.diseno21;
ladeadoDer = R.drawable.diseno23;
ladeadoIzq = R.drawable.diseno22;
disparo = R.drawable.municion1;
break;
case 2130837595:
frontal = R.drawable.diseno31;
ladeadoDer = R.drawable.diseno33;
ladeadoIzq = R.drawable.diseno32;
break;
}
}
public void dispara(View v) {
nave.setImageResource(frontal);
municion.setImageResource(disparo);
municion.setX(nave.getX() + (((nave.getWidth()) / 2) - 5));
municion.setY(nave.getY());
municion.setVisibility(View.VISIBLE);
botonDisparo.setEnabled(false);
manejaDisparo.postDelayed(accionDisparo, 0);
}
Runnable accionDisparo = new Runnable() {
#Override
public void run() {
municion.setY(municion.getY() - 50);
if (llegaAlFinal()) {
municion.setVisibility(View.INVISIBLE);
manejaDisparo.removeCallbacks(accionDisparo);
botonDisparo.setEnabled(true);
}
manejaDisparo.postDelayed(this, 80);
}
};
Runnable accionMovimiento = new Runnable() {
#Override
public void run() {
if (inicioAFin) {
enemigo.setImageResource(R.drawable.enemigodiseno12);
enemigo.setX(enemigo.getX() + movimientoEnemigo);
} else {
enemigo.setImageResource(R.drawable.enemigodiseno13);
enemigo.setX(enemigo.getX() - movimientoEnemigo);
}
if (seSale("izq", "IA") || seSale("der", "IA"))
inicioAFin = !inicioAFin;
manejaEnemigo.postDelayed(this, 80);
}
};
private boolean llegaAlFinal() {
return municion.getY() <= 20;
}
private boolean seSale(String direccion, String jugador) {
switch (direccion) {
case "izq":
switch (jugador) {
case "CU":
return (nave.getX() + movimiento + nave.getWidth()) > findViewById(R.id.activity_main).getWidth();
case "IA":
return (enemigo.getX() + movimiento + enemigo.getWidth()) > findViewById(R.id.activity_main).getWidth();
}
case "der":
switch (jugador) {
case "CU":
return (nave.getX() - movimiento) < 0;
case "IA":
return (enemigo.getX() - movimiento) < 0;
}
}
return true;
}
}
MainActivity.java (activity_main.xml and popup_activity.xml functionality)
package com.example.android.spaceinvaders;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
ImageButton opcionBoton;
private PopupWindow popup;
private RelativeLayout layoutPrincipal;
String[] resultados;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultados = new String[3];
resultados[0] = "fondo3";
resultados[1] = "diseno11";
resultados[2] = "enemigodiseno11";
opcionBoton = (ImageButton) findViewById(R.id.opcion_boton);
layoutPrincipal = (RelativeLayout) findViewById(R.id.principal_screen);
opcionBoton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View vistaPopup = inflater.inflate(R.layout.popup_activity, null);
popup = new PopupWindow(
vistaPopup,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
ImageButton cerrarPop = (ImageButton) vistaPopup.findViewById(R.id.volver_boton);
cerrarPop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popup.dismiss();
opcionBoton.setVisibility(View.VISIBLE);
}
});
popup.showAtLocation(layoutPrincipal, Gravity.BOTTOM, 0, 0);
opcionBoton.setVisibility(View.INVISIBLE);
}
});
}
public void iniciaJuego(View view) {
Intent juego = new Intent(view.getContext(), GameActivity.class);
juego.putExtra("arg", resultados[0] + " " + resultados[1] + " " + resultados[2]);
startActivity(juego);
}
public void actualizaFondo(View vista) {
switch (vista.getId()) {
case R.id.fondo_1:
resultados[0] = "fondo";
break;
case R.id.fondo_2:
resultados[0] = "fondo1";
break;
case R.id.fondo_3:
resultados[0] = "fondo3";
break;
}
}
public void actualizaNave(View vista) {
switch (vista.getId()) {
case R.id.nave_1:
resultados[1] = "diseno11";
break;
case R.id.nave_2:
resultados[1] = "diseno21";
break;
case R.id.nave_3:
resultados[1] = "diseno31";
break;
}
}
public void actualizaEnemigo(View vista) {
switch (vista.getId()) {
case R.id.enemigo_1:
resultados[2] = "enemigodiseno11";
break;
}
}
}
I hope you could help me, please... I don't know where is the error.
The project repository is: github.com/cvazquezlos/Space-Invaders-Android
Thank you so much!
I am writing a simple calculator, but unfortunately it doesn't work.
LogCat says that the error is in my onClick:
at android.view.View$1.onClick(View.java:2072)
But I'm sorry to say I can't find it. So please help me.
activity_main.xml:
<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" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="54dp"
android:layout_marginTop="60dp"
android:ems="10" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="74dp"
android:ems="10" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp"
android:text="Input first number" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText1"
android:layout_marginTop="36dp"
android:text="Input 2nd number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="functionCalculator"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="26dp"
android:text="+"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Your result here" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView3"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/button1"
android:text="Result"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_alignRight="#+id/textView4"
android:text="-"
android:onClick="functionCalculator" />
</RelativeLayout>
ActivityMain.java:
package com.example.caculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText e1,e2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1= (EditText)findViewById(R.id.editText1);
e2 = (EditText)findViewById(R.id.editText2);
t1 = (TextView)findViewById(R.id.textView4);
}
public void functionCalculator(View view) {
int number1 , number2 , result;
if (view.getId()==R.id.button1) {
number1 = Integer.parseInt(e1.getText().toString());
number2 = Integer.parseInt(e2.getText().toString());
result = number1+number2;
t1.setText(Integer.toString(result));
}
if (view.getId()==R.id.button2) {
number1 = Integer.parseInt(e1.getText().toString());
number2 = Integer.parseInt(e2.getText().toString());
result = number1-number2;
t1.setText(Integer.toString(result));
}
}
#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;
}
}
I ran your code and didn't run into any issues as long as I put integers in e1 and e2. As soon as I entered decimal numbers, I ran into exact same issue as you mention. This is because you are trying to parse integers out of the input which may not always be successful and will result in a NumberFormatException. You should write your code so that it never crashes no matter what the case. Just assume your users are idiots. Try the code below, it shouldn't crash:
public void functionCalculator(View view) {
try {
// Firstly checking for integers
int number1, number2;
number1 = Integer.parseInt(e1.getText().toString());
number2 = Integer.parseInt(e2.getText().toString());
if (view.getId() == R.id.button1)
t1.setText(Integer.toString(number1 + number2));
else if (view.getId() == R.id.button2)
t1.setText(Integer.toString(number1 - number2));
} catch (NumberFormatException e) {
float number1, number2;
try {
// Now checking for decimals
number1 = Float.parseFloat(e1.getText().toString());
number2 = Float.parseFloat(e2.getText().toString());
if (view.getId() == R.id.button1)
t1.setText(Float.toString(number1 + number2));
else if (view.getId() == R.id.button2)
t1.setText(Float.toString(number1 - number2));
} catch (NumberFormatException e2) {
// No numbers :(
Toast.makeText(this, "WTF! Enter number here you dingus!", Toast.LENGTH_SHORT).show();
}
}
}
I'm doing a simple calculator in android studio, my code looks like this:
MainActivity.java:
package com.example.ja.calculator;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
String total="";
double v1, v2;
String sign="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void onClick(View v){
Button button = (Button)v;
String str=button.getText().toString();
total+=str;
EditText edit=(EditText)findViewById(R.id.editText);
edit.setText(total);
}
public void OnAdd(View v){
v1 = Double.parseDouble(total);
total = "";
Button button = (Button)v;
String str = button.getText().toString();
sign = str;
EditText edit = (EditText)findViewById(R.id.editText);
edit.setText("");
}
public void OnCalculate(View v){
EditText edit = (EditText)findViewById(R.id.editText);
String str2 = edit.getText().toString();
v2 = Double.parseDouble(str2);
double grand_total = 0;
if(sign.equals("+")){
grand_total = v1 + v2;
}
else if(sign.equals("-")){
grand_total = v1 - v2;
}
else if(sign.equals("x")){
grand_total = v1 * v2;
}
else if(sign.equals(":")){
grand_total = v1 / v2;
}
edit.setText(grand_total+"");
}
public void OnClear(View v){
EditText edit = (EditText)findViewById(R.id.editText);
edit.setText("");
total = "";
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
content main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.ja.calculator.MainActivity"
tools:showIn="#layout/activity_main">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="#+id/button2"
android:layout_alignTop="#+id/button"
android:layout_toRightOf="#+id/button"
android:layout_toEndOf="#+id/button"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:id="#+id/button3"
android:layout_alignTop="#+id/button2"
android:layout_toRightOf="#+id/button2"
android:layout_toEndOf="#+id/button2"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="#+id/button4"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:id="#+id/button5"
android:layout_above="#+id/button2"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6"
android:id="#+id/button6"
android:layout_above="#+id/button3"
android:layout_alignLeft="#+id/button3"
android:layout_alignStart="#+id/button3"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:id="#+id/button7"
android:layout_above="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:id="#+id/button8"
android:layout_alignTop="#+id/button7"
android:layout_toRightOf="#+id/button4"
android:layout_toEndOf="#+id/button4"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="#+id/button9"
android:layout_alignTop="#+id/button8"
android:layout_toRightOf="#+id/button5"
android:layout_toEndOf="#+id/button5"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/button0"
android:layout_below="#+id/button"
android:layout_toRightOf="#+id/button"
android:layout_toEndOf="#+id/button"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="."
android:id="#+id/buttonDot"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:height="80dp"
android:onClick="onClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:id="#+id/buttonEQ"
android:layout_below="#+id/button3"
android:layout_alignLeft="#+id/button3"
android:layout_alignStart="#+id/button3"
android:height="80dp"
android:onClick="OnCalculate" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="#+id/buttonAdd"
android:height="64dp"
android:layout_alignBottom="#+id/buttonEQ"
android:layout_alignLeft="#+id/buttonSub"
android:layout_alignStart="#+id/buttonSub"
android:onClick="OnAdd" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:id="#+id/buttonSub"
android:height="64dp"
android:layout_above="#+id/buttonAdd"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="OnAdd" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x"
android:id="#+id/buttonMul"
android:height="64dp"
android:layout_above="#+id/buttonSub"
android:layout_alignLeft="#+id/buttonSub"
android:layout_alignStart="#+id/buttonSub"
android:onClick="OnAdd" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":"
android:id="#+id/buttonDiv"
android:layout_above="#+id/buttonMul"
android:layout_alignLeft="#+id/buttonMul"
android:layout_alignStart="#+id/buttonMul"
android:height="64dp"
android:onClick="OnAdd" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CE"
android:id="#+id/buttonCE"
android:height="64dp"
android:layout_above="#+id/buttonDiv"
android:layout_toRightOf="#+id/button9"
android:layout_toEndOf="#+id/button9"
android:onClick="OnClear" />
The problem is, when I click some number and after that I click the operation (+,-,/,*) the number clicked before disappears, how to fix it, so I can see full operation, for example 5*5 before clicking "=" and after that changing just for result?
public void OnAdd(View v) {
v1 = Double.parseDouble(total);
total = "";
Button button = (Button) v;
String str = button.getText().toString();
sign = str;
EditText edit = (EditText) findViewById(R.id.editText); ** edit.setText("");
}
The reason for number clicked before gets cleared is that you set text as "". (see **)
You should do the following changes to your code if your calculator to work in the correct way.
public void OnAdd(View v) {
v1 = Double.parseDouble(total);
Button button = (Button) v;
String str = button.getText().toString();
sign = str;
total += str;
EditText edit = (EditText) findViewById(R.id.editText);
edit.setText(total);
}
Now the sign will be appended to the total string. And it will be written back to the editText.
Hi i'm a beginner android developer trying to make a basic calculator app
Here is my layout code from the content_main.xml folder:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<TextView
android:id="#+id/displayer"
android:text="Hello World!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="113dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:id="#+id/minus"
android:onClick="subtract"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/displayer"
android:layout_toStartOf="#+id/displayer"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="add"
android:text="+"
android:id="#+id/plus"
android:layout_below="#+id/minus"
android:layout_alignLeft="#+id/minus"
android:layout_alignStart="#+id/minus" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:onClick="setNumber"
android:tag="1"
android:id="#+id/one"
android:layout_above="#+id/plus"
android:layout_toRightOf="#+id/plus"
android:layout_toEndOf="#+id/plus" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="4"
android:id="#+id/four"
android:tag="4"
android:layout_alignTop="#+id/plus"
android:layout_toRightOf="#+id/plus"
android:layout_toEndOf="#+id/plus" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="2"
android:id="#+id/two"
android:tag="2"
android:layout_above="#+id/four"
android:layout_toRightOf="#+id/one"
android:layout_toEndOf="#+id/one" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="3"
android:tag="3"
android:id="#+id/three"
android:layout_above="#+id/five"
android:layout_toRightOf="#+id/two"
android:layout_toEndOf="#+id/two" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="5"
android:tag="5"
android:id="#+id/five"
android:layout_below="#+id/two"
android:layout_alignLeft="#+id/two"
android:layout_alignStart="#+id/two" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="6"
android:tag="6"
android:id="#+id/six"
android:layout_above="#+id/nine"
android:layout_toRightOf="#+id/five"
android:layout_toEndOf="#+id/five" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="7"
android:tag="7"
android:id="#+id/seven"
android:layout_below="#+id/plus"
android:layout_toRightOf="#+id/plus"
android:layout_toEndOf="#+id/plus" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="8"
android:tag="8"
android:id="#+id/eight"
android:layout_below="#+id/five"
android:layout_alignLeft="#+id/five"
android:layout_alignStart="#+id/five" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setNumber"
android:text="9"
android:tag="9"
android:id="#+id/nine"
android:layout_below="#+id/five"
android:layout_alignLeft="#+id/six"
android:layout_alignStart="#+id/six" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:id="#+id/equal"
android:onClick="equal"
android:layout_below="#+id/plus"
android:layout_alignLeft="#+id/plus"
android:layout_alignStart="#+id/plus" />
</RelativeLayout>
Here is my Activity from the MainActivity folder:
package com.example.android.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private int firstNumber = -1;
private int secondNumber = -1;
private int operation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void equal(View view){
TextView displayerTextView=(TextView)
findViewById(R.id.displayer);
if (operation == 0) {
displayerTextView.setText(firstNumber+secondNumber);
}else if (operation == 1){
displayerTextView.setText(firstNumber-secondNumber);
}else{
displayerTextView.setText("error");
}
}
private void add(View view){
operation = 0;
}
private void subtract(View view){
operation = 1;
}
private void setNumber(View view){
if (firstNumber == -1) {
firstNumber = Integer.parseInt((String)view.getTag());
}else{
secondNumber = Integer.parseInt((String)view.getTag());
}
}
}
When I click on the 3 button in my calculator app this error appears here is the error:
java.lang.IllegalStateException: Could not find a method setNumber(View) in the activity class com.example.android.calculator.MainActivity for onClick handler on view class android.widget.Button with id 'three'
Because you method is private. Change on public.
More you can find here http://developer.android.com/reference/android/widget/Button.html
It should be
public void setNumber(View view){
For the issue mentioned, change
private void setNumber(View view){
if (firstNumber == -1) {
firstNumber = Integer.parseInt((String)view.getTag());
}else{
secondNumber = Integer.parseInt((String)view.getTag());
}
}
to
public void setNumber(View view){
if (firstNumber == -1) {
firstNumber = Integer.parseInt((String)view.getTag());
}else{
secondNumber = Integer.parseInt((String)view.getTag());
}
}
To avoid similar errors in your code with add and subtract, change those functions also from private to public.
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="eBay Search"
android:textSize="13pt"
android:textStyle="bold"
android:textColor="#000099"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</TextView>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:id="#+id/tableLayout">
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Keyword:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<EditText
android:id="#+id/keyword"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
>
</EditText>
</TableRow>
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="Price From:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<EditText
android:id="#+id/from"
android:layout_width="0dp"
android:inputType="numberDecimal"
android:layout_height="wrap_content"
android:layout_weight="3"
>
</EditText>
</TableRow>
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Price To:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<EditText
android:id="#+id/to"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="3"
android:inputType="numberDecimal"
android:layout_width="0dp"
>
</EditText>
</TableRow>
<TableRow
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Sort By:"
android:textSize="10pt"
android:layout_weight="2">
</TextView>
<Spinner
android:id="#+id/sortby"
android:layout_height="wrap_content"
android:prompt="#string/op1"
android:layout_width="fill_parent"
android:entries="#array/sortlist">
</Spinner>
</TableRow>
<TableRow
android:layout_marginTop="15dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/Clear"
android:onClick="clearForm"
android:layout_marginLeft="50dp"
/>
<Button
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="Search"
android:textColor="#color/black"
android:id="#+id/search"
android:layout_marginLeft="50dp"
/>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/keyerror"
android:layout_marginTop="420dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="7pt"
android:textColor="#color/red"
>
</TextView>
<TextView
android:id="#+id/priceerror"
android:layout_marginTop="445dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="7pt"
android:textColor="#color/red"
>
</TextView>
This is the mainactivity code which has onclicklistener method for the search button:
package com.example.hrishikesh.hw9;
import android.app.AlertDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.net.URLEncoder;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int error=0;
EditText text1 = (EditText) findViewById(R.id.keyword);
EditText text2 = (EditText) findViewById(R.id.from);
EditText text3 = (EditText) findViewById(R.id.to);
TextView keyerror = (TextView) findViewById(R.id.keyerror);
TextView priceerror = (TextView) findViewById(R.id.priceerror);
String keyword = text1.getText().toString();
String from = text2.getText().toString();
String to = text3.getText().toString();
String reg = "^[0-9]+$";
if (keyword == null || keyword.length() < 1 || keyword.trim().length() < 1) {
keyerror.setText("Enter a valid keyword");
error=1;
}
else
{
keyerror.setText("");
error=0;
}
if(to.matches(reg) || to.length()==0)
{
}
else
{
priceerror.setText("Enter a valid positive number for maximum price");
error=1;
}
if(from.matches(reg) || from.length()==0)
{
}
else
{
priceerror.setText("Enter a valid positive number for minimum price");
error=1;
}
if(from.length()>0 && to.length()>0)
if(Integer.parseInt(from) - Integer.parseInt(to)>=0){
priceerror.setText("Minimum price has to be less than maximum price");
error=1;
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void clearForm(View v){
EditText text1 = (EditText)this.findViewById(R.id.keyword);
EditText text2 = (EditText)this.findViewById(R.id.from);
EditText text3 = (EditText)this.findViewById(R.id.to);
if (text1 != null) text1.setText("");
if (text2 != null) text2.setText("");
if (text3 != null) text3.setText("");
Spinner spin1 = (Spinner)this.findViewById(R.id.sortby);
spin1.setSelection(0);
}
public void validate(View v){
}
public void search(String keywords,int from,int to,String sortorder){
String url;
int i=0;
url = "http://hrishisaraf-env.elasticbeanstalk.com/";
}
}
Whenever the onclick method gets executed and an error is detected like the keyword being blank. The error text is set and the Search button becomes blank.
No idea why but Setting the width to wrap_content solved the problem.