android 之Toast(吐司)详解


友情链接:菜鸟教程

实例代码:

package com.hsj.example.toastdemo05;

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

public class MainActivity extends AppCompatActivity {

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

    /**
     * 简单土司的用法
     * @param view
     */
    public void simple(View view){
        //1.得到土司对象,传递三个参数:A: 上下文对象;B:土司显示的消息内容;C:土司显示的时长
        //Toast toast=Toast.makeText(this,"我是简单土司",Toast.LENGTH_LONG);
        Toast toast=Toast.makeText(this,"我是简单土司",Toast.LENGTH_SHORT);
        toast.show();
    }

    /**
     * 自定义土司的显示位置
     * @param view
     */
    public void customerPosition(View view){
        Toast toast=Toast.makeText(this,"我是简单土司",Toast.LENGTH_SHORT);
        //自定义土司的显示位置
        //toast.setGravity(Gravity.HORIZONTAL_GRAVITY_MASK,0,0);
        //toast.setGravity(Gravity.CENTER,100,100);
        //toast.setGravity(Gravity.TOP|Gravity.RIGHT,0,0);
        toast.setGravity(Gravity.BOTTOM|Gravity.LEFT,0,0);
        toast.show();
    }

    /**
     * 自定义土司的布局对象
     * @param view
     */
    public void customerView(View view){
        //1.实例化土司对象
        Toast toast=new Toast(this);
        //2.设置土司的显示位置
        toast.setGravity(Gravity.CENTER,0,0);
        //3.设置土司的显示时长
        toast.setDuration(Toast.LENGTH_LONG);
        //4.设置土司显示的内容
        //toast.setText("我是自定义土司");//如果设置土司显示的内容则必须使用Toast.makeText()方法创建土司,否则报异常:This Toast was not created with Toast.makeText()

        View toastView=View.inflate(this,R.layout.customer_toast_view,null);

        ImageView imageView_header= (ImageView) toastView.findViewById(R.id.imageView_header);
        imageView_header.setImageResource(R.drawable.p);

        TextView textView_name= (TextView) toastView.findViewById(R.id.textView_name);
        textView_name.setText("郑爽好美");
        //如果没有给土司设置显示内容,则必须设置土司的view 对象
        toast.setView(toastView);

        //5.显示土司
        toast.show();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37169103/article/details/80652215
今日推荐