Android-Toast

来源:互联网 发布:泰达有线网络客服 编辑:程序博客网 时间:2024/05/17 00:06

Toast的位置,通过 setGravity(int, int, int) 方法来设置。例如,如果想让toast显示在左上角,可以这样设定:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

自定义Toast View
可使用XML或者代码定义一个View layout,通过setView(View) 方法来设置。
例如,创建如下的toast_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:id="@+id/toast_layout_root"              android:orientation="horizontal"              android:layout_width="fill_parent"              android:layout_height="fill_parent"              android:padding="8dp"              android:background="#DAAA"              >    <ImageView android:src="@drawable/droid"               android:layout_width="wrap_content"               android:layout_height="wrap_content"               android:layout_marginRight="8dp"               />    <TextView android:id="@+id/text"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:textColor="#FFF"              /></LinearLayout>

注意LinearLayout元素的ID是”toast_layout_root”。你必须使用此ID 来从 XML inflate布局,如下所示:

LayoutInflater inflater = getLayoutInflater();View layout = inflater.inflate(R.layout.custom_toast,                               (ViewGroup) findViewById(R.id.toast_layout_root));TextView text = (TextView) layout.findViewById(R.id.text);text.setText("This is a custom toast");Toast toast = new Toast(getApplicationContext());toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);toast.setDuration(Toast.LENGTH_LONG);toast.setView(layout);toast.show();

首先,使用getLayoutInflater()(或者getSystemService())获取到 LayoutInflater,然后使用inflate(int, ViewGroup)从XML来inflate布局。第一个参数是布局的资源ID,第二个参数root view。

这里写图片描述

注意:不要使用构造方法来创建Toast,除非要使用setView(View)方法来定义布局。如果你不需要一个自定义的布局,你必须使用 makeText(Context, int, int)来创建Toast。

0 0
原创粉丝点击