Toast Android官方在Android API 30版本(或更高版本)之后即對該方法不生效。
只要SDK版本低于30,Toast.setGravity()方法即可生效
MainActivity.java
package com.example.mytoast;import androidx.appcompat.app.AppCompatActivity;import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private Context context;private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);context = this;//Toast Android官方在Android API 30版本(或更高版本)之后即對該方法不生效。//只要SDK版本低于30,Toast.setGravity()方法即可生效,Toast toast = Toast.makeText(context,"您點擊了按鈕",Toast.LENGTH_SHORT);//彈出位置//Gravity.TOP 頂部 0 0//Gravity.CENTER_VERTICAL 中間toast.setGravity(Gravity.CENTER_VERTICAL,0,0);//自定義 toast/*** LayoutInflater它的作用類似于findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml布局文件,并且實例化;* 而findViewById()是找xml布局文件下的具體widget控件(如 Button、TextView等)。* 具體作用:* 1、對于一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;* 2、對于一個已經載入的界面,就可以使用Activiyt.findViewById()方法來獲得其中的界面元素。* */LayoutInflater layoutInflater = LayoutInflater.from(context);View view = layoutInflater.inflate(R.layout.toast_view,null);LinearLayout linearLayout = view.findViewById(R.id.ll_bg);linearLayout.setBackgroundColor(Color.BLUE);TextView textView =view.findViewById(R.id.btn_tv);textView.setText("自定義彈出框!");ImageView imageView = view.findViewById(R.id.image);imageView.setImageResource(R.mipmap.a);//設置視圖toast.setView(view);//點擊事件button = findViewById(R.id.btn);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//點擊按鈕 顯示彈框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"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="按鈕"android:textSize="24sp"/></LinearLayout>
自定義Toast布局 toast_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:id="@+id/ll_bg"android:layout_height="match_parent"><TextViewandroid:id="@+id/btn_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="24sp"/><ImageViewandroid:id="@+id/image"android:layout_width="68dp"android:layout_height="68dp"/></LinearLayout>