Android

커스텀 토스트 메시지 사용법

Ms_Tony 2015. 10. 8. 11:47

android custom toast 만들기 (사용자 정의 토스트)


<< CommonToast.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
package com.example.samplebutton.util;
 
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
 
import com.example.samplebutton.R;
 
public class CommonToast extends Toast {
    Context mContext;
    public CommonToast(Context context) {
        super(context);
        mContext = context;
    }
 
    public void showToast(String body, int duration){
        LayoutInflater inflater;
        View v;
        if(false){
            Activity act = (Activity)mContext;
            inflater = act.getLayoutInflater();
            v = inflater.inflate(R.layout.toast_layout, null);
        }else// same
            inflater = (LayoutInflater)mContext
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.toast_layout, null);
        }
        TextView text = (TextView) v.findViewById(R.id.text);
        text.setText(body);
 
        show(this,v,duration);
    }
 
    private void show(Toast toast, View v, int duration){
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(duration);
        toast.setView(v);
        toast.show();
    }
 
}


<< toast_layout.xml >>


1
2
3
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/toast_layout_root" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:padding="30dp" 
android:background="@drawable/popup_toast">   
    <textview 
  android:id="@+id/text" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
  android:textsize="18dp" 
  android:textcolor="#ffffff"/>

</linearlayout>


<< MainActivity.java >>


1
2
3
4
5
6
7
8
9
10
11
12
public class MainActivity extends Activity {
    Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
 
        CommonToast toast = new CommonToast(mContext);
        toast.showToast("토스트!!!!", Toast.LENGTH_SHORT);
    }
}

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


출처 : http://androi.tistory.com/103

'Android' 카테고리의 다른 글

안드로이드 공유 기능  (0) 2015.10.16
Android Text ClipBoard에 복사하기  (0) 2015.10.15
확장 리스트뷰(ExpanableListView)  (0) 2015.09.14
Spannable Method(String style, color 변경)  (0) 2015.08.26
레이아웃  (0) 2015.08.20