listener 인터페이스 구현을 위한 anonymous class를 멤버 변수에 넣어서 재활용하여 코드가 무척 간결해졌습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.leeseolhee.calc; | |
import android.support.v7.app.AppCompatActivity; | |
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.TextView; | |
import android.widget.Toast; | |
public class MainActivity extends AppCompatActivity { | |
EditText edit1; | |
EditText edit2; | |
TextView resultTv; | |
Double result; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
edit1 = (EditText)findViewById(R.id.editText); | |
edit2 = (EditText)findViewById(R.id.editText2); | |
resultTv = (TextView)findViewById(R.id.textView); | |
findViewById(R.id.BtnAdd).setOnClickListener(onClickAndCalc); | |
findViewById(R.id.BtnSub).setOnClickListener(onClickAndCalc); | |
findViewById(R.id.BtnMul).setOnClickListener(onClickAndCalc); | |
findViewById(R.id.BtnDiv).setOnClickListener(onClickAndCalc); | |
findViewById(R.id.BtnRem).setOnClickListener(onClickAndCalc); | |
} | |
Button.OnClickListener onClickAndCalc = new View.OnClickListener() { | |
public void onClick(View v) { | |
String tmp1 = edit1.getText().toString(); | |
String tmp2 = edit2.getText().toString(); | |
if(tmp1.equals("") || tmp2.equals("")) { | |
Toast.makeText(getApplicationContext(),"값이 입력되지 않았습니다", Toast.LENGTH_LONG).show(); | |
} | |
else { | |
Double num1 = Double.parseDouble(tmp1); | |
Double num2 = Double.parseDouble(tmp2); | |
switch (v.getId()) { | |
case R.id.BtnAdd: | |
result = num1 + num2; | |
break; | |
case R.id.BtnSub: | |
result = num1 - num2; | |
break; | |
case R.id.BtnMul: | |
result = num1 * num2; | |
break; | |
case R.id.BtnDiv: | |
if (num1 == 0) { | |
Toast.makeText(getApplicationContext(), "0은 나눌수 없습니다.", Toast.LENGTH_LONG).show(); | |
break; | |
} | |
else if(num2 == 0) { | |
Toast.makeText(getApplicationContext(), "0으로 나눌수 없습니다.", Toast.LENGTH_LONG).show(); | |
} | |
else { | |
result = num1 / num2; | |
; | |
break; | |
} | |
case R.id.BtnRem: | |
result = num1 % num2; | |
break; | |
} | |
resultTv.setText("계산결과: " + result.toString()); | |
} | |
} | |
}; | |
} |