安卓之Toast

2018-01-18  本文已影响0人  bluewind1230
设置步骤详见讲义:39/59
package com.example.my_toast;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout linearLayout = findViewById(R.id.liner_item);
//获取局布局View
        View view = LinearLayout.inflate(MainActivity.this,R.layout.item,
                null);
        Toast toast = new Toast(MainActivity.this);
        //设置吐司的View
        toast.setView(view);
        //设置显示时间
        toast.setDuration(Toast.LENGTH_LONG);
        //设置位置
        toast.setGravity(Gravity.TOP|Gravity.CENTER,50,100);
        //显示
        toast.show();
    }
    public void onClick(View view) {

        //获取局布局View
        View view1 = LinearLayout.inflate(MainActivity.this,R.layout.item,
                null);
        Toast toast = new Toast(MainActivity.this);
        //设置吐司的View
        toast.setView(view1);
        //设置显示时间
        toast.setDuration(Toast.LENGTH_LONG);
        //设置位置
        toast.setGravity(Gravity.TOP|Gravity.CENTER,50,100);
        //显示
        toast.show();
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.my_toast.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="弹出Toast"/>

</LinearLayout>

item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/liner_item"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:src="@mipmap/ic_launcher"
        android:layout_width="50dp"
        android:layout_height="30dp" />
    <TextView
        android:id="@+id/text"
        android:textSize="20sp"
        android:text="自定义的Toast,我在item.xml里面"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

上一篇下一篇

猜你喜欢

热点阅读