Toast是一种没有交点,显示时间有限,不能与用户进行交互,用于显示提示信息的显示机制,我们可以把它叫做提示框。Toast不依赖 于Activity,也就是说,没有Activity,依然可以使用Toast。
   Android的四大组件:Activity, Service, Broadcast Receiver, Contet Provider,都是继承Context的(Context,现在大家称之为上下文,之前又被翻译为句柄),包括整个Application也是继承于Context的。Toast就是依赖于应用程序Application的Context。

 

项目结构

android基础---->Toast的使用

 

代码实现

  • MainActivity.java:
package com.example.linux.customtoasttest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * writer: 胡红翔
 * function: 自定义toast,以及toast的简单使用
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // toast:位置的改变
    public void toast1(View view) {
        Toast toast = Toast.makeText(MainActivity.this, "toast", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM | Gravity.LEFT, 0, 0);
        toast.show();
    }

    //toast:自定义Toast
    public void customToast(View view) {
        LayoutInflater inflater = getLayoutInflater();
        ViewGroup viewGroup = (ViewGroup) findViewById(R.id.toast_layout_root);
        View layout = inflater.inflate(R.layout.toast_layout, viewGroup);

        TextView text = (TextView) layout.findViewById(R.id.textView);
        text.setText("This is a custom toast");

        Toast toast = new Toast(MainActivity.this);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout); // 自定义View
        toast.show();
    }
}
  •  activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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:orientation="vertical"
    tools:context="com.example.linux.customtoasttest.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="ToastPosition"
        android:onClick="toast1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:text="CustomToast"
        android:onClick="customToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
View Code

相关文章:

  • 2022-12-23
  • 2021-09-20
  • 2021-06-20
  • 2021-06-23
  • 2021-08-26
  • 2021-08-17
  • 2021-05-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案