반응형

안녕하세요. 애드소프트 입니다.

 

오늘은 토스트 사용법에 대해 알아 보겠습니다.

 

토스트(Toast)는 사용자에게 짧은 메시지 형식으로 팝업과 비슷한 형태의 오버레이 창에 메시지를 표시합니다.

메시지 전달을 위해 사용하고 일정시간 지나면 자동으로 사라집니다. 쉽게 말해 단순한 의사전달 팝업 정도로 이해하시면 될 것 같습니다.

 

android developer 발췌

 

 

Toast(토스트) 사용하기

 

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        TextView content;
        public ViewHolder(View view) {
            super(view);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast alertToast = Toast.makeText(view.getContext(), getContentTextView().getText(), Toast.LENGTH_SHORT );
                    alertToast.show();
                }
            });

            title = view.findViewById(R.id.item_tv_title);
            content = view.findViewById(R.id.item_tv_content);
        }

        public TextView getContentTextView() {
            return content;
        }
    }

 

상단 예제는 RecylerView의 아이템을 눌렀을 경우 토스트 메시지를 표시하는 샘플 코드입니다.

 

이 예는 대부분의 토스트 메시지 알림에 필요한 모든 것을 보여주며, 이 외에 필요한 것은 거의 없습니다. 그러나 토스트 메시지의 위치를 다르게 지정하거나 단순한 SMS 대신 자체 레이아웃을 사용하는 것이 좋습니다.

 

토스트 메시지 위치 지정

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

위치를 오른쪽으로 살짝 이동하려면 두 번째 매개변수의 값을 올리고, 아래로 조금 이동하려면 마지막 매개변수의 값을 올립니다.

 

맞춤 토스트 메시지 뷰 만들기

단순한 텍스트 메시지로 충분하지 않다면 토스트 메시지 알림용으로 맞춤설정된 레이아웃을 만들 수 있습니다. 맞춤 레이아웃을 만들려면 XML 또는 애플리케이션 코드에 뷰 레이아웃을 정의하고 루트 View 객체를 setView(View) 메서드에 전달합니다.

다음 스니펫에는 토스트 메시지 알림용으로 맞춤설정된 레이아웃이 포함되어 있습니다(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 요소의 ID는 'custom_toast_container'임을 확인하세요. 다음과 같이 이 ID와 XML 레이아웃 파일 'custom_toast'의 ID를 사용하여 레이아웃을 확장해야 합니다.

 

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();

 

먼저 getLayoutInflater()(또는 getSystemService())를 사용하여 LayoutInflater를 가져온 다음 inflate(int, ViewGroup)

사용하여 XML에서 레이아웃을 확장합니다.

첫 번째 매개변수는 레이아웃 리소스 ID이고 두 번째는 루트 뷰입니다.

이 확장된 레이아웃을 사용하여 레이아웃에서 더 많은 뷰 객체를 찾을 수 있으므로 이제 ImageView와 TextView 요소의 콘텐츠를 캡처하고 정의할 수 있습니다.

마지막으로 Toast(Context)를 사용하여 새 토스트 메시지를 만들고 토스트 메시지의 일부 속성(예: 중력 및 지속 시간)을 설정합니다.

그런 다음 setView(View)를 호출하고 확장된 레이아웃을 전달합니다.

이제 show()를 호출하여 맞춤 레이아웃으로 토스트 메시지를 표시할 수 있습니다.

 

참고 : developer.android.com/guide/topics/ui/notifiers/toasts

반응형

+ Recent posts