public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Event();
}
//添加点击事件
private void Event() {
// TODO Auto-generated method stub
findViewById(R.id.bt_1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showToast1();
}
});
findViewById(R.id.bt_2).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showToast2();
}
});
findViewById(R.id.bt_3).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showToast3();
}
});
findViewById(R.id.bt_4).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showToast4();
}
});
}
/*
* *默认输出Toast
*/
protected void showToast1() {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(this,R.string.app_name,Toast.LENGTH_LONG);
toast.show();
}
/*
* *自定义位置Toast
*/
protected void showToast2() {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(this,"改变位置的Toast!",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, -100, -100);//改变Toast的位置
toast.show();
}
/*
* *带图片Toast
*/
protected void showToast3() {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(this,"带有图片的Toast!",Toast.LENGTH_LONG);
LinearLayout toast_layout = (LinearLayout)toast.getView();
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.item2);
toast_layout.addView(iv, 0);
toast.show();
}
/*
* *完全自定义Toast
*/
protected void showToast4() {
// TODO Auto-generated method stub
/*
* *将xml转化为View对象
*/
LayoutInflater inflater = LayoutInflater.from(this);
View toast_view = inflater.inflate(R.layout.toast_layout, null);
Toast toast = new Toast(this);
toast.setView(toast_view);
toast.show();
}
}<pre name="code" class="html">//toast_layout布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/item2"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hahah"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义的Toast"/>
</LinearLayout>
多种Toast实现
最新推荐文章于 2023-07-31 17:42:16 发布