4 분 소요

위젯

Button

image

버튼

버튼의 더 많은 속성을 알고 싶다면 들어가서 확인해보자.

Button의 XML 속성

<Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        android:text="버튼입니다"
/>

TIP

보통 layout_width와 layout_height는 layout을 꾸밀 때마다 나오는 구성요소들 중 하나이다. 웬만하면 32dp 같은 구체적인 숫자를 쓰지말고 비율을 쓰거나 wrap_content 혹은 match_parent를 쓰도록 하자. 왜냐면 핸드폰 기기마다 화면의 크기가 다르고 제공해주는 해상도가 다르기 때문이다.

id 속성

  • id 속성은 모든 위젯의 아이디를 나타낸다.
  • layout에서 구성한 위젯을 자바 코드로 끌고와서 동작을 시키기 위해서는 id를 이용해 가져온다.
위젯 변수 = (위젯형) findViewById(R.id.위젯id);
Button Btn;
Btn = (Button) findViewById(R.id.btn1);
  • 이 코드가 xml에서 형성한 Button 위젯을 끌고온 코드이다. xml에서 Id를 btn1으로 정해주었기 때문에 java 코드로 넘어와서 타입 캐스팅을 해주고 위젯의 아이디 btn1을 가져온다.
  • R.id.btn1 에서 R은 resource 폴더를 의미한다.
setContentView(R.layout.activity_main);
  • onCreate 부분에서 activity_main이라는 layout을 끌고 왔기 때문에 R.id. 으로 접근이 가능하다.

문제 1

버튼을 클릭했을때 배경색이 빨간색으로 변하게 해보자.

image

activity_main.xml 코드

<?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"
    android:orientation="vertical"
    android:id="@+id/lay1"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="버튼입니다"
        />

</LinearLayout>

MainActivity 코드

public class MainActivity extends AppCompatActivity {
    Button Btn;
    LinearLayout Lay;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Btn = (Button) findViewById(R.id.btn1);
        Lay = (LinearLayout) findViewById(R.id.lay1);

        Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Lay.setBackgroundColor(Color.RED);
            }
        });
    }
}

코드 설명

  • 우리가 쓸 것은 버튼과 그 뒤의 배경인 LinearLayout이다. 그러므로 버튼과 LinearLayout에 id 값을 매겨주자.
  • 버튼의 배경색은 초록색이다. 배경을 건들고 싶으면 xml상에서 android:backgroun=”” 을 건들여 주면 된다. 안에 들어가는 값은 #000000 인데 앞의 00은 R이며 중간 00은 G 뒤에 00은 B이다. 0을 f로 채워주면 그 색깔을 쓴다는 것이다.
  • 메인 엑티비티에서 Button과 LinearLayout의 id 속성을 끌고 온다.
  • Btn.setOnClickListener의 onClick 함수는 버튼을 클릭했을때 어떠한 행위가 이루어지게끔 오버라이딩을 해준다.
  • LinearLayout의 Id를 끌고와 저장한 변수인 Lay에 setBackgrounColor 함수를 이용해 버튼을 클릭했을때 Red가 되게끔 설계해준다.

EditText, TextView, Button

XML 속성

<?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"
    android:orientation="vertical"
    android:id="@+id/lay1"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text1"
        android:text="텍스트뷰 입니다."/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit1"
        android:hint="여기에 글자를 쓰세요."/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="확인"/>

</LinearLayout>

image

Padding

TIP

위 그림을 보면 뭔가 꽉 차고 정돈 되지 않은 느낌이다. 이러한 것을 padding 하나로 해결할 수 있다.

<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"
    android:orientation="vertical"
    android:id="@+id/lay1"
    tools:context=".MainActivity"
    android:padding="30dp">

image

  • 이런 식으로 LinearLayout쪽에 padding 값을 30dp만큼 주면 위, 양 옆, 아래로 30dp 만큼 적당히 떼어줘서 훨씬 정돈된 느낌이 든다.

  • LinearLayout이 TextView, EditText, Button 세개를 감싸고 있으므로 이 세개를 한덩어리로 보고 사방으로 30dp씩 띄워주는 것이다.

  • 그렇다면 각 위젯 안에다가 padding을 줄 수는 없을까??

  • 위젯 안에는 padding 대신에 layout_margin 이라고 하는 것을 준다.

Margin

TIP

위의 코드처럼 여러개의 위젯을 묶고 있을 때는 padding을 써서 한번에 여백을 주고, 한 위젯씩 여백을 주고 싶다면 layout_margin을 줘야한다.

<?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"
    android:orientation="vertical"
    android:id="@+id/lay1"
    tools:context=".MainActivity"
    android:padding="30dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/text1"
        android:text="텍스트뷰 입니다."
        android:layout_margin="20dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit1"
        android:hint="여기에 글자를 쓰세요."
        android:layout_margin="20dp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn1"
        android:text="확인"
        android:layout_margin="20dp"/>

</LinearLayout>

image

  • 각 위젯마다 20dp 씩 여백을 준 결과다.

문제 2

총 4개의 Button을 구성하고 1개의 EditText와 1개의 TextView를 구성하라

image

  • 버튼 1 클릭 : 버튼 1 45도 회전
  • 버튼 2 클릭 : 1번 클릭하면 버튼 4가 투명색으로 클릭 못하게끔, 1번 더 클릭하면 버튼 4가 원래대로 돌아오게
  • 버튼 3 클릭 : 밑에 EditText에 글자가 쓰여져 있다면 그 글자를 TextView에 출력
  • 버튼 4 클릭 : 버튼 4를 제외한 버튼을 다 사라지게끔 만들기

activity_main.xml 코드

<?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"
    android:orientation="vertical"
    android:id="@+id/lay1"
    tools:context=".MainActivity"
    android:padding="30dp">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Btn1"
        android:text="버튼 1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Btn2"
        android:text="버튼 2"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Btn3"
        android:text="버튼 3"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Btn4"
        android:text="버튼 4"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Edit1"
        android:hint="입력하시오."/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/Text1"
        android:text="결과 : "
        android:textSize="20dp"/>
</LinearLayout>

MainActivity 코드

public class MainActivity extends AppCompatActivity {
    Button Btn1;
    Button Btn2;
    Button Btn3;
    Button Btn4;
    EditText Edit1;
    TextView Text1;
    int rotate = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Btn1 = (Button) findViewById(R.id.Btn1);
        Btn2 = (Button) findViewById(R.id.Btn2);
        Btn3 = (Button) findViewById(R.id.Btn3);
        Btn4 = (Button) findViewById(R.id.Btn4);
        Edit1 = (EditText) findViewById(R.id.Edit1);
        Text1 = (TextView) findViewById(R.id.Text1);

        Btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rotate += 45;
                Btn1.setRotation(rotate);
            }
        });

        Btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Btn4.isEnabled() == true)
                    Btn4.setEnabled(false);
                else
                    Btn4.setEnabled(true);
            }
        });

        Btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Text1.setText("결과 : " + Edit1.getText());
            }
        });

        Btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Btn1.getVisibility() == View.INVISIBLE) {
                    Btn1.setVisibility(View.VISIBLE);
                    Btn2.setVisibility(View.VISIBLE);
                    Btn3.setVisibility(View.VISIBLE);
                }
                else {
                    Btn1.setVisibility(View.INVISIBLE);
                    Btn2.setVisibility(View.INVISIBLE);
                    Btn3.setVisibility(View.INVISIBLE);
                }
            }
        });


    }
}

코드 설명

  • 버튼 1을 클릭하면 45도 회전하게끔 만들어야 하니깐 onCreate 밖에 int형 변수 하나를 선언해주고 버튼 1이 클릭될 때마다 45씩 더해주면서 setRotation 함수를 호출해주고 파라미터에 넣어준다.
  • 버튼을 투명색으로 클릭 못하게 해주는 것에는 enabled가 있다. xml 상에서 enabled가 “false”로 되어있으면 투명색으로 되어지는데 자바 코드에서 직접 건들이려면 setEnabled 함수를 쓰면 된다.
  • isenabled()가 true이면 투명하지 않다는 뜻이여서 클릭하면 투명색으로 바꿔주고 반대로 false이면 투명하다는 뜻이기에 투명하지 않게 바꾸어준다.
  • EditText에 써있는 글자를 가져오려면 getText 함수를 이용하면 된다.
  • TextView 글자를 수정하려면 setText 함수를 써서 파라미터에 string 형을 넣어주면 된다.
  • 버튼의 보이기에는 옵션이 3가지가 있는데 Visible, Invisible, Gone이 있다. Invisible이 되면 버튼만 없어지고 버튼이 차지하는 위치는 그대로 있지만, Gone을 쓰게 되면 버튼이 없어지면서 그 위치를 다른 위젯이 알아서 채우게 된다.
  • 버튼의 visibility를 가져오는 함수는 getVisibility이다.

댓글남기기