Toast 自定义

protected void onCreate(Bundle savedInstanceState) {
    // TODO 自动生成的方法存根
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);
    LayoutInflater inflater = getLayoutInflater();
    View layoutView = inflater.inflate(R.layout.activity_main, (ViewGroup)findViewById(R.id.toast_layout_root));
    TextView textView = (TextView)layoutView.findViewById(R.id.text);
    textView.setText("This is a custom toast");
    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_SHORT);
    toast.setView(layoutView);
    toast.show();

    <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:background="#DAAA"
    android:id="@+id/toast_layout_root"
    android:orientation="horizontal">

<ImageView 
    android:src="@drawable/progress_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="8dp"/>

<TextView
    android:id="@+id/text"
    android:textColor="#FFF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>
自定义 Toast 的布局,可以按照以下步骤操作: 1. 创建一个 XML 布局文件,用于定义 Toast 的外观。例如,创建一个名为 "custom_toast.xml" 的文件。 2. 在 XML 布局文件中,添加你希望在 Toast 中显示的视图和样式。可以使用任何布局和视图组件,如 TextView、ImageView 等。例如,可以在布局中添加一个 TextView 来显示文本内容。 ```xml <!-- custom_toast.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:background="@drawable/toast_background"> <TextView android:id="@+id/toast_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="14sp" android:text="This is a custom Toast" /> </LinearLayout> ``` 3. 在代码中使用自定义布局来创建 Toast。在你想要显示 Toast 的地方,添加以下代码: ```java // 创建一个 LayoutInflater 对象 LayoutInflater inflater = getLayoutInflater(); // 加载自定义布局文件 View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_container)); // 创建 Toast 对象 Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); // 显示 Toast toast.show(); ``` 以上代码会加载自定义布局文件,并将其设置为 Toast 的视图,然后显示 Toast。你可以根据需要修改自定义布局文件和代码中的内容,以适应你的具体需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值