自定Toast
效果图
动画准备:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >
<item android:drawable="@drawable/desktop_rocket_launch_1" android:duration="300" />
<item android:drawable="@drawable/desktop_rocket_launch_2" android:duration="300" />
</animation-list>
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:background="@drawable/rocket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lv_toat"
android:layout_centerInParent="true"
/>
</RelativeLayout>
主要的步骤:
- 自定义布局文件;以帧动画为例进行,演示;
- 定义Window的参数;
- 将视图加载到窗体;
- 给自定Toast设置监听事件 OnTouchListener;
- 获取Toast位置,进行判断,并进行并进行更新;
代码如下:
package com.example.toast;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
public class MainActivity extends Activity {
private WindowManager wm;
private View view;
private LayoutParams params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//获取窗体的管理器
wm = (WindowManager) getSystemService(WINDOW_SERVICE);
//加载自定义的View,加载帧动画
view = View.inflate(this, R.layout.item_toast, null);
view.setBackgroundResource(R.drawable.rocket);
AnimationDrawable an = (AnimationDrawable) view.getBackground();
an.start();
//设置窗体的相关的参数;
params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT; //高度
params.width = WindowManager.LayoutParams.WRAP_CONTENT;//宽度
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.format = PixelFormat.TRANSLUCENT;
params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;//窗体的类型
view.setOnTouchListener(new OnTouchListener() {
int sindex = 0;
int sindey = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
sindex = (int) event.getRawX();
sindey = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int eindex = (int) event.getRawX();
int eindey = (int) event.getRawY();
params.x+=(eindex-sindex);
params.y+= (eindey-sindey);
wm.updateViewLayout(view, params);
sindex=eindex;
sindey = eindey;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
wm.addView(view, params);
}
}
需要添加权限;