本期话题教你如何自定义Toast对话框
在androd中弹出一个Toast对话框是一个非常easy的事情,几乎是一句话就可以搞定,但是有没有想过为Toast添加一些新的花样,比如改变它的位置(放到界面中间或是顶部),或是改变它的内容(加图片..),其实这些都是可以实现的,今天就来说说如何弹出一个不一样的Toast对话框!
先看效果图:
再上代码:
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast mToast;
switch (v.getId()) {
case R.id.button1:
mToast = Toast.makeText(this, "我是默认的Toast", Toast.LENGTH_SHORT);
mToast.show();
break;
case R.id.button2:
mToast = new Toast(MainActivity.this);
mToast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout mLinearLayout = new LinearLayout(this);
TextView mTextView = new TextView(this);
mTextView.setText("在TextView的左边给一图片");
mTextView.setGravity(Gravity.CENTER_VERTICAL);// 设置文字居中
mTextView.setTextSize(13);
mTextView.setTextColor(Color.WHITE);
mTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_launcher, 0, 0, 0);// 就相当于在XML中写android:drawableLeft属性
mLinearLayout.setBackgroundResource(android.R.drawable.toast_frame);// toast_frame就是系统的toast的背景图片
mLinearLayout.addView(mTextView);// 添加textview到linearLayout中
mToast.setView(mLinearLayout);// 让linearLayout在toast中显示
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
break;
case R.id.button3:
mToast = new Toast(this);
mToast.setGravity(Gravity.CENTER, 0, 0);
View view = LayoutInflater.from(this).inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.linear));//填充布局
ImageView mImageView = (ImageView) view.findViewById(R.id.imageView);
mImageView.setImageResource(R.drawable.ic_launcher);
TextView mText = (TextView) view.findViewById(R.id.textView1);
mText.setText("这是自定义布局的吐司!");
mToast.setView(view);
mToast.show();
break;
default:
break;
}
}
}
button1是默认的,button2是使图片和文字在同一行显示,很多app也有这种效果,button3是通过自定义布局的方式来显示Toast,button4是默认的。在代码中都有注释,很简单,不难!
custom_toast是自定义的布局,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/imageView"
android:textSize="14sp" />
</RelativeLayout>