11 吐司 Toast 代码案例

时间:2022-09-05 10:29:17
package com.qf.day11_toast_demo05;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

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


public void MyOnclick1(View v){
//Toast.makeText(MainActivity.this, "==Toast=>", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, "==Toast=>", 1).show();
}

public void MyOnclick2(View v){
//Toast.makeText(MainActivity.this, "==Toast=>", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "==Toast=>", 0).show();
}

//自定义Toast
public void MyOnclick3(View v){
//
//View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout, null);
//
//TextView tv = (TextView) view.findViewById(R.id.tv);
//
//tv.setText("Hello world 王国");

TextView tv = new TextView(MainActivity.this);
tv.setTextColor(Color.RED);
tv.setTextSize(30);
tv.setText("先定个小目标");

//得到Toast对象
Toast toast = new Toast(MainActivity.this);

//设置布局样式
toast.setView(tv);
//展示toast的时间
toast.setDuration(Toast.LENGTH_SHORT);
//设置展示的位置 参数1:展示的位置 参数2:x轴偏移量 参数3;Y轴偏移量
toast.setGravity(Gravity.TOP, 0, 0);
//展示Toast
toast.show();

}

}