点击弹出居中带图片和背景的Toast
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view){
Toast toast = Toast.makeText(this, "我是自定义吐司", Toast.LENGTH_LONG);
//设置Toast显示的位置
toast.setGravity(Gravity.CENTER,0,0);
//获取Toast的窗口对象,并把它强制转换为LinearLayout布局
LinearLayout ll=(LinearLayout) toast.getView();
//设置Toast背景红色
ll.setBackgroundColor(Color.RED);
//设置Toast里面内容显示的位置
//ll.setGravity(Gravity.CENTER);
//动态生成控件
ImageView iv=new ImageView(this);
//指定生成控件的宽高
iv.setLayoutParams(new LinearLayout.LayoutParams(300,300));
//给ImageView赋图片
iv.setImageResource(R.mipmap.ic_launcher);
//把ImageView添加到布局
ll.addView(iv);
//把设置完的布局文件填充给Toast
toast.setView(ll);
//显示Toast
toast.show();
}
}
布局只需一个Button即可
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="org.frxm.toast.MainActivity">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="弹出Toast"
android:onClick="click"
/>
</RelativeLayout>