Android入门之Toast的使用教程

  package org.mk.android.demosimpletoast;

  import androidx.appcompat.app.AppCompatActivity;

  import android.content.Context;

  import android.os.Bundle;

  import android.view.Gravity;

  import android.view.LayoutInflater;

  import android.view.View;

  import android.view.ViewGroup;

  import android.widget.Button;

  import android.widget.ImageView;

  import android.widget.TextView;

  import android.widget.Toast;

  public class MainActivity extends AppCompatActivity {

  private Button btnShowToast;

  private Button btnShowCustomToast;

  private Context ctx;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  ctx = MainActivity.this;

  btnShowToast = (Button) findViewById(R.id.btnShowToast);

  btnShowToast.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View view) {

  Toast.makeText(MainActivity.this, "提示的内容", Toast.LENGTH_SHORT).show();

  }

  });

  btnShowCustomToast = (Button) findViewById(R.id.btnShowCustomToast);

  btnShowCustomToast.setOnClickListener(new View.OnClickListener() {

  @Override

  public void onClick(View view) {

  midToast("这是一个自定义的toast",Toast.LENGTH_SHORT);

  }

  });

  }

  private void midToast(String str, int showTime) {

  LayoutInflater inflater = getLayoutInflater();

  View view = inflater.inflate(R.layout.view_toast_custom, (ViewGroup) findViewById(R.id.mkToast));

  ImageView img_logo = (ImageView) view.findViewById(R.id.toastBiaoQing);

  TextView tv_msg = (TextView) view.findViewById(R.id.toastMsg);

  tv_msg.setText(str);

  Toast toast = new Toast(ctx);

  toast.setGravity(Gravity.CENTER, 0, 0);

  toast.setDuration(Toast.LENGTH_LONG);

  toast.setView(view);

  toast.show();

  }

  }