PopupWindow这个类用来实现一个弹出框,可以使用任意布局,悬浮于activity之上,
实现如所示效果:长按nihao弹出删除(渐变进入和退出),点击删除则清除nihao 文字。
代码:
public class MainActivity extends Activity {
private TextViewtv_pup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_pup = (TextView) findViewById(R.id.tv_pup);
tv_pup.setOnLongClickListener(new OnLongClickListener() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public boolean onLongClick(View v) {
//获取控件的位置
int[]location1=newint[2];
tv_pup.getLocationOnScreen(location1);
Log.i("test",location1[0]+"OnScreen"+location1[1]);
//获取控件的宽高
intx=tv_pup.getWidth();
inty=tv_pup.getHeight();
Log.i("test",x+"控件宽高"+y);
//创建popwindow
View inflate = View.inflate(MainActivity.this, R.layout.pup_view,null);
final PopupWindowpop = new PopupWindow(inflate,LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//设置外部可点击,pop消失
pop.setOutsideTouchable(true);
pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//设置动画效果
pop.setAnimationStyle(R.style.popup_anim_clear);
//设置显示位置
pop.showAtLocation(tv_pup,Gravity.LEFT|Gravity.TOP,x/2-10, location1[1]-y);
//点击pop上的组件事件
inflate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//点击pop去除tv_pup里面的内容
tv_pup.setText("");
//pop消失
pop.dismiss();
}
});
return false;
}
});
}
}
设置动画效果步骤(入场和出场动画):
pop.setAnimationStyle(R.style.popup_anim_clear);
1.在styles文件中添加如下节点
<stylename="popup_anim_clear">
<itemname="android:windowEnterAnimation">@anim/popup_enter</item>
<itemname="android:windowExitAnimation">@anim/popup_exit</item>
</style>
2.在res目录新建anim文件夹,在anim中创建
popup_enter.xml入场动画
popup_exit出场动画
渐变入场
<?xmlversion="1.0"encoding="utf-8"?>
<alphaxmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0"
android:toAlpha="1"
android:duration="1000">
</alpha>
渐变出场
<?xmlversion="1.0"encoding="utf-8"?>
<alphaxmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1"
android:toAlpha="0"
android:duration="1000">
</alpha>