android中Toast做为一个很好的用户交互的工具,在很多应用中都有应用,但是普通的Toast样式很单一,只能用于显示文字,在某些应用中单调的Toast往往显得不是那么好,
不过还好,android给我们提供了可以自定的Toast,大家可以根据自己的需要定制自己的样式,这样就可以满足我们的需要了。
首先关键也就是在布局文件中,这里以显示图片和文字为例。
toast布局文件 custome_toast_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
;android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/ivForToast"
;android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tvForToast"
;android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
代码文件
package test.androidyue.custom_toast;
//导入必要的包文件
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomeToastActivity extends Activity {
/** Called when the activity is first created. */
private Button btnTest;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.initializeViews();
}
/*
* 初始化需要的控件
*/
privatevoid initializeViews(){
this.initializeButtons();
}
/*
* 初始化需要的button
*/
private void initializeButtons(){
this.btnTest=(Button)findViewById(R.id.btnTest);
this.btnTest.setOnClickListener(new BtnTestOnClickListener());
}
/*
* button单击事件监听器类
*/
class BtnTestOnClickListener implements View.OnClickListener{
@Override
public void onClick(View arg0) {
//显示toast
showCustomToast();
}
}
/*
* 从布局文件中加载布局并且自定义显示Toast
*/
private void showCustomToast(){
//获取LayoutInflater对象,该对象可以将布局文件转换成与之一致的view对象
LayoutInflater inflater=getLayoutInflater();
//将布局文件转换成相应的View对象
View layout=inflater.inflate(R.layout.custome_toast_layout,(ViewGroup)findViewById(R.id.toast_layout_root));
//从layout中按照id查找imageView对象
ImageView imageView=(ImageView)layout.findViewById(R.id.ivForToast);
//设置ImageView的图片
imageView.setBackgroundResource(R.drawable.right);
//从layout中按照id查找TextView对象
TextView textView=(TextView)layout.findViewById(R.id.tvForToast);
//设置TextView的text内容
textView.setText("This is Toast but cannot be eaten and hello world");
//实例化一个Toast对象
Toast toast=new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);
toast.show();
}
}