EditText 위젯을 사용하여 사용자에게 데이터를 받을수 있다.
# 현재까지는 사용자가 앱에서 이 부분을 클릭하면 이름을 입력하기 위해 Name을 지우고 입력해야한다.
# 이름 외에도 이메일, 비밀번호, 숫자 등 다양한 형식을 받을수있다.
코드에서 inputType을 바꿀수있다.
text를 지우고 hint를 입력하여 이름을 입력하는 공간이라는것을 알려줄수있다.
# 이제 사용자가 그냥 이름을 입력할수있다.
이렇게 사용자가 입력한 텍스트는 getText로 가져올수있다.
String name = editName.getText().toString().trim();
# toString으로 문자열화 했다.
# trim으로 주위의 공백들을 제거했다.
그리고 가져온 데이터를 텍스트뷰에 넣을수있다.
textResult.setText(name);
# 텍스트뷰에 넣기 위해서는 무조건 문자열로 넣어줘야 한다.
더보기

사용된 앱:
# 어떤 숫자의 퍼센트를 구하는 계산기 앱
TextView textTip;
EditText editPercent;
EditText editNumber;
Button button;
TextView textResult;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textTip = findViewById(R.id.textTip);
editPercent = findViewById(R.id.editPercent);
editNumber = findViewById(R.id.editNumber);
button = findViewById(R.id.button);
textResult = findViewById(R.id.textResult);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textTip.setVisibility((View.GONE));
textResult.setVisibility(View.VISIBLE);
String percentStr = editPercent.getText().toString();
String numberStr = editNumber.getText().toString();
double percent = Double.valueOf(percentStr).intValue();
double number = Double.valueOf(numberStr).intValue();
Log.i("CalcApp","Percent : "+percent);
Log.i("CalcApp","Number : "+number);
double result = number*percent/100.0;
String resultStr = String.valueOf(result);
textResult.setText(resultStr);
editPercent.setText("");
editNumber.setText("");
// 버튼 클릭횟수 5 마다 토스트로 보여주기
count = count + 1;
if (count % 5 == 0){
Toast toast = Toast.makeText(getApplicationContext(),count+"회 계산했습니다. 결과는" + resultStr+" 입니다.",Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP,0,0);
toast.show();
}
}
});
}

'Android' 카테고리의 다른 글
[Android] 퀴즈 앱 실습: 앱이 종료되는 버그 처리, 프로그레스 바, portrait, landscape (0) | 2022.07.11 |
---|---|
[Android] UI 이미지, 레이아웃 편집: scale, LinearLayout (0) | 2022.07.08 |
[Android] 기본적인 UI 활용: text, background, layout, margin, padding, gravity, visibility (0) | 2022.07.08 |
[Android] 주사위 앱 실습: 오픈소스 라이브러리 적용 (0) | 2022.07.08 |
[Android] 주사위 앱 실습: 아이콘, 앱 이름, 액션바, 로그, findViewById, setOnClickListener (0) | 2022.07.07 |
댓글