Android PopupWindow 简单用法
程序员文章站
2022-05-14 08:06:39
...
可上下移动的TextView,左侧是一个PopupWindow跟随其移动
DragTextView.java
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastTouchedY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int distanceY = (int) (event.getRawY() - lastTouchedY);
if (distanceY != 0) {
FrameLayout.MarginLayoutParams curParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
int topMargin = (curParams.topMargin + distanceY);
if (topMargin + getHeight() > ((ViewGroup) getParent()).getHeight()) {
topMargin = ((ViewGroup) getParent()).getHeight() - getHeight();
}
if (topMargin < 0) {
topMargin = 0;
}
curParams.topMargin = topMargin;
setLayoutParams(curParams);
lastTouchedY = event.getRawY();
}
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
private HideSubtitlePopupWindow popupWindow;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Log.d(TAG, "onLayout: " + changed + "---left=" + left + "---top=" + top + "---right=" + right + "---bottom=" + bottom);
//
int popWidth = SizeUtils.dp2px(30);
int popHeight = SizeUtils.dp2px(30);
int popLeft = -popWidth;
int popTop = -popHeight - (getHeight() - popHeight) / 2;
Log.d(TAG, "onLayout: popLeft=" + popLeft + "---popTop=" + popTop);
if (popupWindow == null) {
popupWindow = new HideSubtitlePopupWindow(getContext(), popWidth, popHeight);
popupWindow.showAtLocation(this, Gravity.NO_GRAVITY, popLeft, popTop);
}
popupWindow.update(this, popLeft, popTop, -1, -1);
}
HideSubtitlePopupWindow.java
public class HideSubtitlePopupWindow extends PopupWindow {
public HideSubtitlePopupWindow(Context context, int width, int height) {
LayoutInflater inflater = LayoutInflater.from(context);
View mView = inflater.inflate(R.layout.hide_subtitle_popup_view, null);
this.setContentView(mView);
this.setWidth(width);
this.setHeight(height);
this.setAnimationStyle(R.style.PopScaleAnimation);
this.setFocusable(false);
this.setOutsideTouchable(false);
TextView textView = mView.findViewById(R.id.tvText);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
listener.onClick();
}
}
});
}
public interface OnClickListener {
void onClick();
}
private OnClickListener listener;
public void setListener(OnClickListener listener) {
this.listener = listener;
}
}
上一篇: JDK生成HTTPS证书
下一篇: 基于UDP网络编程的服务器和客户端