Development/Android

13. Message(Toast,SnackBar)

궁선이 2018. 5. 5. 01:40

오늘은 화면에 메세지를 띄우는 법을 포스팅 하겠습니다.

포스팅할 메세지 종류는

1. 일반 Toast 메세지
2. 위치지정 Toast 메세지
3. Custom Toast메세지
3. SnackBar 메세지

이렇게 4가지 입니다.

1. 일반 Toast 메세지


일반 토스트 메세지는 매우 쉽습니다.

Toast.makeText(getApplicationContext() ,"일반 메세지 창입니다.",Toast.LENGTH_SHORT).show(); //인자로는 (Context,메세지,표시될시간) 이렇게 구성되어 있습니다. //또는 Toast toast = Toast.makeText(getApplicationContext() ,"일반 메세지 창입니다.",Toast.LENGTH_SHORT); toast.show(); //위와 같이 사용하셔도 됩니다.
2. 위치지정 Toast메세지


다음과 같이 좌측상단 모서리를 기준으로 x,y만큼의(10,20) 거리에서 팝업을 해줍니다.
기준 위치(첫번째 인자)는 변경하여 줄 수 있습니다.

Toast toastView = Toast.makeText(getApplicationContext(), "위치지정 메세지 입니다.", Toast.LENGTH_SHORT); toastView.setGravity(Gravity.LEFT|Gravity.TOP,10,20); toastView.show();
3. Custom Toast 메세지


먼저 간단하게 Toast에 띄울 레이아웃을 제작합니다.

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/txtmsg" android:layout_width="match_parent" android:layout_height="50dp" android:text="레이아웃 토스트 제작입니다." android:gravity="bottom" android:background="#e9abab"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button"/> </LinearLayout>

그 다음은 다음과 같이 Toast에 레이아웃을 달아줍니다.

View view = getLayoutInflater().inflate(R.layout.mytoast,null); TextView tv = (TextView)view.findViewById(R.id.txtmsg); tv.setText("레이아웃으로 만든 토스트 창 입니다."); Toast toastView = new Toast(getApplicationContext()); toastView.setDuration(Toast.LENGTH_SHORT); toastView.setGravity(Gravity.CENTER,0,100); toastView.setView(view); toastView.show();
4. SnakBar 메세지

위 사진의 하단에 팝업되는 형태의 메세지 입니다.

SnackBar는 다른 메세지와는 달리 설정을 해주어야 합니다.
File->Project Structure -> app -> Dependencies 
위 경로로 들어가셔서
다음 + 버튼을 눌러 창을 띄워줍니다.

그리고 나면 다음과 같은 창이 나타납니다.
검색창에 design을 검색하고 맨 위에 "com.android.support.design" 이라는 항목을
선택하고 OK를 눌러줍시다.(버전상관 없습니다)

그리고

Snackbar.make(v,"SnackBar로 보여주는 메세지 입니다.",Snackbar.LENGTH_SHORT) .setAction("OK", new View.OnClickListener() { @Override public void onClick(View v) { } }).show();

위와같이 코드를 입력해주면 완료입니다.

감사합니다ㅎ