Toast制作的四种样式 (默认,自定义位置,图片+文字,自定义)

 效果如图所示:



Activity1.java文件 (主入口文件)


package com.yongninggo.helloworld;

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

import static android.widget.Toast.makeText;
//程序主入口文件
public class Activity1 extends AppCompatActivity {

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

        toast1();
        toptoast();
        imagetoast();
        zidingyi();
    }

    private void zidingyi() {
        findViewById(R.id.Toast4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zidingyi44();
            }


        });
    }

    private void imagetoast() {
        findViewById(R.id.Toast3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imagetoast33();
            }
        });
    }

    private void toptoast() {
        findViewById(R.id.Toast2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toptoast22();
            }
        });
    }

    private void toast1() {
        findViewById(R.id.Toast1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toast11();
            }
        });
    }
    private void toast11() {
        makeText(this,"Toast",Toast.LENGTH_SHORT).show();
    }
    private void toptoast22() {
       Toast toast = Toast.makeText(this,"toptoast",Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP,0,0);
        toast.show();
    }

    private void imagetoast33() {
        Toast toast = Toast.makeText(this,"imagetoast",Toast.LENGTH_SHORT);

        LinearLayout toast_layout = (LinearLayout) toast.getView();
        ImageView iv = new ImageView(this);
        iv.setImageResource(R.drawable.image1);
        toast_layout.addView(iv,0);

        toast.show();
    }

    private void zidingyi44() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View toast_view = inflater.inflate(R.layout.toast_layout,null);
        Toast toast = new Toast(this);
        toast.setView(toast_view);
        toast.show();
    }
}


activity1.xml布局文件





    


toast_layout.xml文件  (自定义toast布局文件)




    
        
        
    






你可能感兴趣的:(Android)