1.写一个类.toast能够显示的关键在与windowMainger 的addview方法. 和remove方法.
自定义toast代码
public class LocationToast implements OnTouchListener {
private Context context;
WindowManager mWM;
private float startX;
private float startY;
private TextView textView;
private WindowManager.LayoutParams params;
public LocationToast(Context context) {
this.context = context;
params = new WindowManager.LayoutParams();
// 视图的高度
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
// 视图的宽度
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
// 图片的格式
params.format = PixelFormat.TRANSLUCENT;
// 设置显示的类型
params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
// | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE 不可触摸
}
public void show(String text) {
//得到窗口管理器
mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (textView == null) {
textView = (TextView) View.inflate(context, R.layout.view_location, null);
textView.setBackgroundResource(R.drawable.location_bg0);
}
textView.setText(text);
textView.setOnTouchListener(this);
//通过这个方法,把view添加动窗口
mWM.addView(textView, params);
}
public void hide() {
if (textView != null) {
if (textView.getParent() != null) {
//通过这个方法把view从窗口移除
mWM.removeView(textView);
}
textView = null;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// 获取事件的类型
switch (event.getAction()) {
// 手指按下
case MotionEvent.ACTION_DOWN:
// 获取起始点的坐标
startX = event.getRawX();
startY = event.getRawY();
break;
// 手指移动
case MotionEvent.ACTION_MOVE:
// 获取当前点的坐标
float currentX = event.getRawX();
float currentY = event.getRawY();
// 移动的距离
float gapX = currentX - startX;
float gapY = currentY - startY;
params.x += gapX;
params.y += gapY;
startX = currentX;
startY = currentY;
mWM.updateViewLayout(textView, params);
break;
}
return false;
}
}
2..主页面的代码
public class MainActivity extends AppCompatActivity {
private LocationToast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToast = new LocationToast(this);
}
public void go(View view) {
mToast.show("你好吗");
}
}
3.主页面的布局和toast的布局
<RelativeLayout
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"
tools:context="com.example.mytoastdemo.MainActivity">
<Button
android:onClick="go"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/location"
android:padding="8dp"
android:text="fdjlsk" >
</TextView>