안슈/2강/if문 활용2

텍스트 입력후 버튼 클릭시 

"홍길동" 입력했다면, "남자" 텍뷰에 출력

"성춘향" 입력했다면, "여자" 텍뷰에 출력

둘다 아니면 "모르겠습니다" 텍뷰에 출력

 

xml코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".MainActivity"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이름을 입력하세요"/>
    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/bt"
        android:text="성별확인"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
 
</LinearLayout>
 
 

 

 

자바 코드 설명
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.example.myapplication02;
 
 
 
public class MainActivity extends AppCompatActivity {
 
    Button bt;//bt는 버튼타입이다!
    TextView tv;//tv는 텍뷰 타입이다!
    EditText et;//et는 에딧텍스트 타입이다!
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        bt = findViewById(R.id.bt); 
//bt변수 / [=]넣어라 /찾아서 뷰를 아이디로(리소스 경로에. 아이디는. bt인) [=xml파일에 bt아이디를 가진애를]
        tv = findViewById(R.id.tv);
        et = findViewById(R.id.et);
 
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { //bt를 클릭하면 {}를 실행해라
                if(et.getText().toString().equals("홍길동")) {
                    tv.setText("남자");
//만약 (et에서.텍스트를 가져와라. String타입으로. 같은지 비교해라("홍길동")과)가 true면
//{ tv에. 텍스트를 정해라("남자")로 }
                }
                else if(et.getText().toString().equals("성춘향")){
                    tv.setText("여자");
                }
                else{
                    tv.setText("모르겠습니다.");
                }
            }
        });
    }
}
 
 

댓글

Designed by JB FACTORY