android 自定义Toast显示风格

转自   点击打开链接

我自己有稍作修改

1.创建一个自己想要显示Toast风格的XML如下代码(toast_xml.xml):



        
        
 
  
 
  

2.封装一个Toast共同类,当然也可以直接在activity运用,那么我是用共通类,当然只是简单的封装:

public class My_Toast {

    private static My_Toast my_toast;

    private Toast toast;

    private My_Toast(){
    }

    public static My_Toast createToastConfig(){
        if (my_toast==null) {
            my_toast = new My_Toast();
        }
        return my_toast;
    }

    public void ToastShow(Context context,ViewGroup root,String tvString){

        View layout = LayoutInflater.from(context).inflate(R.layout.toast_xml, root,false);//这里的false有必要添加,不然报错

        TextView text = (TextView) layout.findViewById(R.id.toast_id);
        text.setText(tvString);
        toast = new Toast(context);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

}

 
  
 
  

3.创建一个Activity去引用该共通类:

import com.sbr.commonView.ToastCommom;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class ToastActivity extends Activity {
	
	private Button mbutton;
	
	private ToastCommom toastCommom;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.toast_buton);
		toastCommom = ToastCommom.createToastConfig();
		mbutton = (Button) findViewById(R.id.btn);
		mbutton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				toastCommom.ToastShow(ToastActivity.this, (ViewGroup)findViewById(R.id.toast_layout_root(这里是将要包含该组件的父类组件id)), "你好");
			}
		});
		
	}
	
}


好了,一个简单的自定义toast显示就完成了;当然万变不离其宗,都是类似的做法。


你可能感兴趣的:(经验积累,android)