android 自定义Toast & 如何使Toast随Activity消失而消失

自定义toast(包括带图片的toast以及 自定义底色和边框的Toast)

自定义位置的toast

在Activity中创建一个toast对象,然后:
	toast = Toast.makeText(getApplicationContext(), "自定义位置Toast",Toast.LENGTH_LONG);
	toast.setGravity(Gravity.CENTER, 0, 0);
	toast.show();

带图片和文字的toast

代码如下:
toast = Toast.makeText(getApplicationContext(), "带图片的Toast",Toast.LENGTH_LONG);
	toast.setGravity(Gravity.CENTER, 0, 0);

	LinearLayout toastView = (LinearLayout) toast.getView();
	ImageView image = new ImageView(getApplicationContext());
	image.setImageResource(R.drawable.ic_launcher);
	toastView.addView(image, 0);
	toast.show();


自定义边框以及底色的toast

btn_test_toast5.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				View toastRoot = getLayoutInflater().inflate(R.layout.my_toast,
						null);
                                // 圆角 灰色背景
				Toast toast = new Toast(getApplicationContext());
				toast.setView(toastRoot);
				toast.show();
			}
		});
在 my_toast布局文件中:



    
    
     


在my_border.xml文件中:



    
    

    

    

    
    

下载地址:
http://download.csdn.net/detail/lowtec_dream/6835043


如何使toast随Activity消失而消失?


findViewById(R.id.btn_toast).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 只创建一个Toast对象
				if (toast != null) {
					count++;
					toast.setText(str + "count:" + count);
					toast.setDuration(Toast.LENGTH_LONG);
					toast.show();
				} else {
					count++;
					toast = Toast.makeText(MainActivity.this, str + "count:"
							+ count, duration);
					toast.show();
				}
			}
		});

@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			if (toast != null) {
				toast.cancel();
			}
			
		}
		return super.onKeyDown(keyCode, event);
	}

// 只创建一个Toast对象,在合适的地方把Toast给cancel()就可以了。
2014-11-20 17:53:33




转载于:https://www.cnblogs.com/jinfenglee/p/4388723.html

你可能感兴趣的:(android 自定义Toast & 如何使Toast随Activity消失而消失)