屏幕上的Android位置元素
问题描述:
我有一个列表视图,当用户按下一个按钮时,我想收集按钮的坐标并将一个编辑文本放在屏幕上方的顶部。当用户点击屏幕上的任何其他位置时,edittext将消失,并且会触发一种方法,该方法使用用户输入框中的数据。我会如何去做这样的事情?我想要一些类似于QuickActions的东西,但不像侵入式那样。有人能指出我至少如何去获得按钮坐标的方向吗?屏幕上的Android位置元素
答
好吧,所以这里是我已经能够实现我想要做的事情。是否有可能动态地放置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非常重要,如果您不使用它,您将无法在框外单击以关闭它。
现在,它的奇怪。我必须在框外点击两次以关闭窗口。第一次点击似乎突出了我的文本框,第二次点击实际上关闭了它。任何人都知道为什么会发生这种情况?
答
凌乱,取决于您的视图层次结构。 getLeft()方法(以及getRight,getTop和getBottom)都与控件的View父级有关。看看getLocationOnScreen,看看它是否做到了你想要的。
getLocationOnScreen似乎为我提供了x和y坐标。实际上我坚持如何膨胀视图并将其放置在屏幕上。有任何想法吗? – ryandlf
这取决于底层的ViewGroup:如果您使用的是LinearLayout或RelativeLayout之类的东西,那么确实没有什么好方法可以做到绝对定位。你可能会尝试的是在左上角的位置膨胀它,将尺寸设置为你想要的值,然后根据x和y坐标设置边距以将其移动到位。很乱,但... – Femi
所以没有setAtThisLocation(x,y)方法,我可以使用on.a视图对象?我会玩你的想法并发布我的结果。谢谢。 – ryandlf