我有一个列表视图,当用户按下按钮时,我想收集按钮的坐标,并在屏幕上放置一个编辑框,它会被充气到其正上方。当用户点击屏幕上的其他任何地方时,编辑框将消失,并触发使用用户输入到框中的数据的方法。如何做这样的事情?我想要类似于QuickActions的东西,但不太显眼。有人能指导我至少如何获得按钮坐标吗?
好的,这是我能够实现我想做的事情的方法。是否可以在不调整边距等内容的情况下动态放置PopupWindow。
public void showPopup(View view, View parentView, final int getId, String getLbs){
int pWidth = 100;
int pHeight = 80;
int vHeight = parentView.getHeight(); //The listview rows height.
int[] location = new int[2];
view.getLocationOnScreen(location);
final View pView = inflater.inflate(R.layout.list_popup, null, false);
final PopupWindow pw = new PopupWindow(pView, pWidth, pHeight, false);
pw.setTouchable(true);
pw.setFocusable(true);
pw.setOutsideTouchable(true);
pw.setBackgroundDrawable(new BitmapDrawable());
pw.showAtLocation(view, Gravity.NO_GRAVITY, location[0]-(pWidth/4), location[1]+vHeight);
final EditText input = (EditText)pView.findViewById(R.id.Input);
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.i("Focus", "Focus Changed");
if (hasFocus) {
//Shows the keyboard when the EditText is focused.
InputMethodManager inputMgr = (InputMethodManager)RecipeGrainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
inputMgr.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}
}
});
input.setText("");
input.requestFocus();
Log.i("Input Has Focus", "" + input.hasFocus());
pw.setOnDismissListener(new OnDismissListener(){
@Override
public void onDismiss() {
changeWeight(getId, Double.parseDouble(input.getText().toString()));
Log.i("View Dismiss", "View Dismissed");
}
});
pw.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
Log.i("Background", "Back Touched");
pw.dismiss();
return true;
}
return false;
}
});
}
pWidth和pHeight是我选择的PopupWindow的大小,vHeight是我从onCreate上下文中收集到的主父视图的高度。请记住,这不是完美的代码。我仍然需要添加一些东西,比如动画效果以及一个漂亮的小箭头或其他东西来显示窗口与哪个元素相关联。setBackgroundDrawable非常重要,如果您不使用它,将无法在框外单击关闭它。
现在,情况有点奇怪。我必须在框外点击两次才能关闭窗口。第一次单击似乎只是突出显示我的文本框,而第二次单击实际上将其关闭。有人知道为什么会发生这种情况吗?
根据你的View层级,可能会比较混乱。getLeft()方法(以及getRight、getTop和getBottom方法)都相对于控件的View父级。看一下getLocationOnScreen方法,看它是否符合你的要求。