반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리

Android Toast 정리

2016. 9. 7. 22:32 | Posted by 솔웅


반응형

Toasts



Toast 는 LogCat 과 함께 Android App을 개발하면서 간단하게 테스트 할 때 유용하게 사용되는 기능입니다.
관련된 Android API Guide 는 이곳에서 보실 수 있습니다.


https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Basics



If user response to a status message is required, consider instead using a Notification 



The Basics



makeText() 메소드를 사용해 Toast 객체를 초기화합니다. 이 메소드는 3개의 파라미터를 갖습니다. (the application Context, the text message, and the duration for the toast)
show()를 사용해서 toast notification을 display 할 수 있습니다.

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast
.show();



이 예제 형식을 가장 많이 사용합니다. 다른 형식은 거의 사용할 일이 없을 겁니다. Toast 메세지의 표시 위치를 다르게 한다거나 Toast 메세지의 layout 을 여러분이 원하는 대로 꾸미고 싶을 경우 추가적으로 코딩을 하면 됩니다.

아래와 같이 한줄로 처리할 수 있습니다.

Toast.makeText(context, text, duration).show();



Positioning your Toast



기본적으로 Toast notification은 화면의 아랫쪽 중앙에 표시됩니다. 이 위치를 바꿀 수 있는데요. setGravity(int, int, int) 메소드를 사용하시면 됩니다.
이 메소드는 3개의 파라미터를 갖습니다. (a Gravity constant, an x-position offset, and a y-position offset)

예를 들어 toast가 top-left 에 표시되기를 원하시면 아래와 같이 하면 됩니다.

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);



오른쪽으로 좀 옮기고 싶으면 두번째 파라미터의 값을 높이면 됩니다. 아랫쪽으로 옮기고 싶으면 마지막 파라미터의 값을 올리면 됩니다.



Creating a Custom Toast View



메세지가 간단하지 않으면 layout을 customize 할 수 있습니다. custom layout을 만들려면  View layout을 XML 파일에 정의해야 합니다. 혹은 어플리케이션 안에 정의 할 수도 있ㅅ브니다. 그리고 root ViewsetView(View) 메소드로 pass 합니다.

예제 (saved as layout/custom_toast.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
             
android:id="@+id/custom_toast_container"
             
android:orientation="horizontal"
             
android:layout_width="fill_parent"
             
android:layout_height="fill_parent"
             
android:padding="8dp"
             
android:background="#DAAA"
             
>
   
<ImageView android:src="@drawable/droid"
               
android:layout_width="wrap_content"
               
android:layout_height="wrap_content"
               
android:layout_marginRight="8dp"
               
/>
   
<TextView android:id="@+id/text"
             
android:layout_width="wrap_content"
             
android:layout_height="wrap_content"
             
android:textColor="#FFF"
             
/>
</LinearLayout>



LinearLayout element의 ID는 "custom_toast_container" 입니다. 이 xml 파일의 이름은 custom_toast 이구요.




LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
               
(ViewGroup) findViewById(R.id.custom_toast_container));

TextView text = (TextView) layout.findViewById(R.id.text);
text
.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast
.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast
.setDuration(Toast.LENGTH_LONG);
toast
.setView(layout);
toast
.show();



우선 이 xml layout 파일을 inflate 시켰습니다. 그리고 infalte 시킬때 위에 언급한 ID 인 custom_toast_container 를 사용했구요.
이러면 해당 LinearLayout 이 성공적으로 inflate 되게 됩니다.
getLayoutflater() (혹은 getSystemService()) 를 사용해 LayoutInflater를 retrieve 합니다. 그리고 inflate(int, ViewGroup) 을 사용해서 layout 을 inflate 시키구요.
첫번째 파라미터는 layout resource의 ID 이구요. 두번째는 root View 입니다. 이 inflate 된 layout 에 다른 View 객체들을 넣을 수 있는데요. 여기서는 TextView를 넣었습니다. Image View를 넣을 수도 있습니다.

마지막으로 Toast(Context)를 사용해서 새로운 Toast를 생성하고 property들을 세팅합니다. 여기서는 Gravity 와 Duration을 세팅했습니다. 그 다음은 setView(View) 를 호출하고 이것을 inflate 된 layout에 pass 합니다. 이렇게 하면 show() 를 사용해서 customize 된 layout으로 toast를 표시할 수 있게 됩니다.

Note: Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast.



반응형