<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="2" android:columnCount="2"
android:layout_margin="5dp"
>
<TextView
android:text="학번"
android:layout_marginRight="5dp"
/>
<EditText android:id="@+id/hakbun"
android:layout_columnWeight="1"
android:hint="학번을 입력하세요" />
<Button android:id="@+id/show_hakbun"
android:layout_columnSpan="2"
android:layout_columnWeight="1"
android:text="학번 보여 주기" />
</GridLayout>
</LinearLayout>
package com.example.project6_1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText hakbun;
Button show_hakbun;
String hakbun_in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hakbun = findViewById(R.id.hakbun);
show_hakbun = findViewById(R.id.show_hakbun);
show_hakbun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hakbun_in = hakbun.getText().toString();
Toast.makeText(getApplicationContext(), hakbun_in, Toast.LENGTH_SHORT).show();
}
});
}
}
학번을 입력하면 toast메세지로 출력하는 앱이다.
버튼을 눌러도 공백 메세지만 보인다.
분명 editText에 getText string으로 잘 바꿔서 가지고 왔는데 왜 이러는걸까?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hakbun = findViewById(R.id.hakbun);
show_hakbun = findViewById(R.id.show_hakbun);
//!!!!hakbun_in = hakbun.getText().toString();
show_hakbun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), hakbun_in, Toast.LENGTH_SHORT).show();
}
});
}
분명 문제가 있었다.
주석처리한 부분
hakbun_in = hakbun.getText().toString();
이 한 줄을 setOnClickListener 바깥에 입력할 경우
앱을 실행하자마자 editText에 있는 공백이 hakbun_in변수에 들어가는 것이다.!!
그래서 Toast메세지를 출력했을 때 공백만 나오는 이유였다.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hakbun = findViewById(R.id.hakbun);
show_hakbun = findViewById(R.id.show_hakbun);
show_hakbun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hakbun_in = hakbun.getText().toString(); //이벤트실행되는 블럭안!
Toast.makeText(getApplicationContext(), hakbun_in, Toast.LENGTH_SHORT).show();
}
});
}
따라서 다음과 같이 setOnClickListener블럭 안쪽으로 옮겨야한다.
그럼 실행이 잘된다.