Android自定制Toast显示外观



Android自定制Toast显示外观

Android原生的Toast只是提供一个简单的文本显示消息。有些单调乏味。不过,Android Toast本身也充分提供了对Toast可定制化的方案,那就是Toast的setView()方法。比如,可以自己在代码中从一个布局文件加载一个view,然后装载到Toast中作为Toast的view显示,如代码所示:

private	void	showMyToast(){
		LayoutInflater inflater =this.getLayoutInflater();
		View view = inflater.inflate(android.R.layout.simple_list_item_2,null);
		view.setBackgroundColor(Color.RED);
		TextView text1=(TextView) view.findViewById(android.R.id.text1);
		text1.setText("Toast 1");
		text1.setTextColor(Color.WHITE);
		TextView text2=(TextView) view.findViewById(android.R.id.text2);
		text2.setText("Toast 2");
		text2.setTextColor(Color.YELLOW);
		
		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL,0,0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(view);
		toast.show();
	}


运行结果如图所示:

Android自定制Toast显示外观



Android自定制Toast显示外观

Android原生的Toast只是提供一个简单的文本显示消息。有些单调乏味。不过,Android Toast本身也充分提供了对Toast可定制化的方案,那就是Toast的setView()方法。比如,可以自己在代码中从一个布局文件加载一个view,然后装载到Toast中作为Toast的view显示,如代码所示:

private	void	showMyToast(){
		LayoutInflater inflater =this.getLayoutInflater();
		View view = inflater.inflate(android.R.layout.simple_list_item_2,null);
		view.setBackgroundColor(Color.RED);
		TextView text1=(TextView) view.findViewById(android.R.id.text1);
		text1.setText("Toast 1");
		text1.setTextColor(Color.WHITE);
		TextView text2=(TextView) view.findViewById(android.R.id.text2);
		text2.setText("Toast 2");
		text2.setTextColor(Color.YELLOW);
		
		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL,0,0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(view);
		toast.show();
	}


运行结果如图所示:

Android自定制Toast显示外观