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


<< CommonToast.java >>

   
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){
		// http://developer.android.com/guide/topics/ui/notifiers/toasts.html
		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 >>


   
    
    


<< MainActivity.java >>


   
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


+ Recent posts