Toast & Snackbar

토스트메세지

 정의

일반적으로 어떤 알림을 주기위해서 화면의 하단에 잠깐 보였다가 사라지는게 토스트메세지입니다.


여기서는 토스트메세지의 기본보다는 좀더 심화방법에 대해서 다루어 보겠습니다.

 

1.토스트 메세지의 위치설정 

예시 코드를 통해서 설명하도록 하겠습니다.

1
2
3
4
5
6
Toast toast=Toast.makeText(getApplicationContext(),"위치가 바뀐 토스트",Toast.LENGTH_LONG);
//기본적인 토스트 메세지를 만들어줍니다.
toast.setGravity(Gravity.TOP|Gravity.LEFT,200,200);
//setGravity( 처음 기준점, x축 offset, y축 offset)을 사용하여 위치조정
toast.show();
//
cs

 

2. 토스트 메세지의 모양설정


토스트 메세지의 모양은 기본적으로 toast.setView(View)를 통해서 설정할 수 있습니다.
여기선 shapeDrawable을 통해서 TextView의 모양을 만들고 이 TextView를 포함한 레이앙를 토스트에 설정해서 토스트메세지로 TextView가 출력되도록 하겠습니다.

우선 textView를 넣어둘 toastborder.xml파일입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/toast_layout_root">
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textSize="40dp"
        android:background="@drawable/toast"/>
<!--이 배경은 커스터마이징한겁니다-->
 
</LinearLayout>
cs


우리는 이안에 있는 TextView를 토스트로 출력해볼겁니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
LayoutInflater inflater=getLayoutInflater();
    //여기선 R.layout에 toastborder.xml파일을 만들고 그 안에 TextView를 만들어 줍니다
 
    View layout=inflater.inflate(R.layout.toastborder,(ViewGroup)findViewById(R.id.toast_layout_root));
    //layoutInflater : xml로 정의된 resource들을 view의 형태로 반환해줌
    TextView textView=(TextView)layout.findViewById(R.id.text);
    //반환된 레이아웃에서 해당 텍스트를 가져옵니다.
    textView.setText("모양을 바꾼 토스트입니다");
    //텍스트의 글자를 설정합니다.
    Toast toast=new Toast(getApplicationContext());
    //토스트를 출력할 context를 설정합니다.
    toast.setGravity(Gravity.CENTER,0,-100);
    toast.setDuration(Toast.LENGTH_LONG);
    //토스트의 여러 특성을 설정합니다.
    toast.setView(layout);
    //토스트의 뷰를 우리가 뽑았던 레이아웃으로 설정합니다.
    toast.show();
cs

 

스낵바

정의

스낵바 또한 알림을 위해 사용되는 메세지 출력입니다. 그러나 그 기본형태는 토스트와 다르게 아래에서 올라오듯이 출력되며, 출력 유지, 시간 등 토스트보다 세부사항이 설정가능합니다.

주의: 스낵바를 사용하기위해선 Project struture , Dependency에서 design라이브러리를 등록해야합니다.
 

 

예제: 버튼을 클릭하면 스낵바가 출력되도록하는 코드입니다.
1
2
3
4
5
6
7
Button button2=(Button)findViewById(R.id.button4);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v,"스낵바입니다",Snackbar.LENGTH_LONG).show();
//만드는형식은 토스트와 아주 유사합니다. 그러나 첫번째 인자로 해당 뷰를 출력해야합니다.
// 그럼 해당 뷰의 parent뷰를 그 뷰를 출력대상으로 설정합니다.
            }
        });
cs

 

아래는 모두 합한예제 파일입니다.

MainActivity.java

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
45
46
47
48
49
50
51
52
53
54
55
package com.jasonlee.ed_with_android_studio;
 
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast toast=Toast.makeText(getApplicationContext(),"위치가 바뀐 토스트",Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP|Gravity.LEFT,200,200);
                toast.show();
            }
        });
        Button button1=(Button)findViewById(R.id.button3);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater inflater=getLayoutInflater();
                //layoutInflater : xml로 정의된 resource들을 view의 형태로 반환해줌
                View layout=inflater.inflate(R.layout.toastborder,(ViewGroup)findViewById(R.id.toast_layout_root));
                TextView textView=(TextView)layout.findViewById(R.id.text);
                textView.setText("모양을 바꾼 토스트입니다");
                Toast toast=new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER,0,-100);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();
 
            }
        });
        Button button2=(Button)findViewById(R.id.button4);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v,"스낵바입니다",Snackbar.LENGTH_LONG).show();
            }
        });
    }
}
 
cs


toast.xml (이건 drawable에 저장합니다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="4dp"
        android:color="#ffffff00"/>
    <solid
        android:color="#ff883300"/>
    <padding
        android:left="20dp"
        android:right="20dp"
        android:top="20dp"
        android:bottom="20dp"
        />
    <corners
        android:radius="15dp"/>
</shape>
cs


table_layout.xml (TextView가 저장된 레이아웃)

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
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:stretchColumns="0,1,2">
    android:stretchColumns: make assigned colum full
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <TextView
            android:text="Name : "
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            />
 
 
    </TableRow>
    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="NO"
            android:layout_column="1"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NO"
            android:layout_column="2"
            />
 
    </TableRow>
</TableLayout>
cs


Activity_main.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
 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">
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="토스트 띄우기"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="토스트 모양바꾸기"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="324dp"
        />
 
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="99dp"
        android:text="스낵바띄우기"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
 
cs

 

+ Recent posts